1

I am starting my script locally via:

sudo python run.py remote

This script happens to also open a subprocess (if that matters)

webcam = subprocess.Popen('avconv -f video4linux2 -s 320x240 -r 20 -i /dev/video0 -an -metadata title="OfficeBot" -f flv rtmp://6f7528a4.fme.bambuser.com/b-fme/xxx', shell = True)

I want to know how to terminate this script when I SSH in.

I understand I can do:

sudo pkill -f "python run.py remote"

or use:

ps -f -C python

to find the process ID and kill it that way.

However none of these gracefully kill the process, I want to able to trigger the equilivent of CTRL/CMD C to register an exit command (I do lots of things on shutdown that aren't triggered when the process is simply killed).

Thank you!

Titan
  • 5,567
  • 9
  • 55
  • 90

2 Answers2

3

You should use "signals" for it:

http://docs.python.org/2/library/signal.html

Example:

import signal, os

def handler(signum, frame):
    print 'Signal handler called with signal', signum

signal.signal(signal.SIGINT, handler)
#do your stuff

then in terminal:

kill -INT $PID

or ctrl+c if your script is active in current shell

http://en.wikipedia.org/wiki/Unix_signal

also this might be useful:

How do you create a daemon in Python?

Community
  • 1
  • 1
fsw
  • 3,595
  • 3
  • 20
  • 34
  • This works great for the main process, however my subprocess continues to output: def killme(signum, frame): webcam.kill() sys.exit() – Titan May 19 '13 at 22:37
2

You can use signals for communicating with your process. If you want to emulate CTRL-C the signal is SIGINT (which you can raise by kill -INT and process id. You can also modify the behavior for SIGTERM which would make your program shut down cleanly under a broader range of circumstances.

Thomas Fenzl
  • 4,342
  • 1
  • 17
  • 25