开发者

How to stop a multi-threaded Python script from outside

I have a Python program that uses multiple daemon threads. I want to stop the program from outside, preferably from another Python script.

I've tried with kill <pid> from shell, just for a test, but it doesn't work with multi-threaded scripts.

One way would be to开发者_C百科 make the program check some file every n-seconds as a flag for termination. I'm sure there's some better way I can do this.

Note that I'd like to stop the program cleanly, so some message from outside in a form of an exception would be ideal, I think.

EDIT:

Here's an example of how I did it at the moment:

try:
    open('myprog.lck', 'w').close()
    while True:
        time.sleep(1)
        try:
            open('myprog.lck').close()
        except IOError:
            raise KeyboardInterrupt
except KeyboardInterrupt:
    print 'MyProgram terminated.'

Deleting file myprog.lck will cause the script to stop. Is the example above bad way to do this?


Use the poison pill technique. Upon receipt of a pill (a special message) your program must handle it and die.. The way you're doing it its ok, but for something more elegant, you should implement a kind of communication between your "killing script" and your main program. For a start, have a look in the standard library for Interprocess Communication and Networking.


I would install a signal handler as described in http://www.doughellmann.com/PyMOTW/signal/index.html#signals-and-threads

You can enter kill -l in your shell to get a list of available signals.


You should be able to kill it from the shell with kill -9 <pid>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜