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!

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

This works great for the main process, however my subprocess continues to output: def killme(signum, frame): webcam.kill() sys.exit()
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.