开发者

Graceful exiting of a program in Python?

开发者 https://www.devze.com 2022-12-17 09:33 出处:网络
I have a script that runs as a while True: doStuff() What开发者_高级运维 is the best way to communicate with this script if I need to stop it but I don\'t want to kill it if it is in the middle of

I have a script that runs as a

while True:
  doStuff()

What开发者_高级运维 is the best way to communicate with this script if I need to stop it but I don't want to kill it if it is in the middle of an operation?


And I'm assuming you mean killing from outside the python script.

The way I've found easiest is

@atexit.register
def cleanup()
  sys.unlink("myfile.%d" % os.getpid() )

f = open("myfile.%d" % os.getpid(), "w" )
f.write("Nothing")
f.close()
while os.path.exists("myfile.%d" % os.getpid() ):
  doSomething()

Then to terminate the script just remove the myfile.xxx and the application should quit for you. You can use this even with multiple instances of the same script running at once if you only need to shut one down. And it tries to clean up after itself....


The best way is to rewrite the script so it doesn't use while True:.

Sadly, it's impossible to conjecture a good way to terminate this.

You could use the Linux signals.

You could use a timer and stop after a while.

You could have dostuff return a value and stop if the value is False.

You could check for a local file and stop if the file exists.

You could check an FTP site for a remote file and stop of the file exists.

You could check an HTTP web page for information that indicates if your loop should stop or not stop.

You could use OS-specific things like semaphores or shared memory.


I think the most elegant would be:

keep_running = true
while keep_running:
    dostufF()

and then dostuff() can set keep_running = false whenever in no longer wants to keep running, then the while loop ends, and everything cleans up nicely.


If that's a console aplication and exiting by pressing Ctrl+C is ok, could that solve your problem?

try:
  while True:
    doStuff()
except KeyboardInterrupt:
  doOtherStuff()

I guess the problem with that approach is that you wouldn't have any control exactly when and where in doStuff the execution is terminated.


Long time ago I've implemented such a thing. It catches Ctrl+C (or keyboard interrupt). It uses my package snuff-utils.

To install:

pip install snuff-utils
from snuff_utils.graceful_exit import graceful_exit

while True:
    do_task_until_complete()
    if graceful_exit:
        do_stuff_before_exit()
        break

On Ctrl+C it will log:

An interrupt signal has been received. The signal will be processed according to the logic of the application.

The goal I was after is to exit program but only after finishing already running task.

Be careful with multiprocessing/multithreading. It is not tested.


The signal module can trap signals and react accordingly?

0

精彩评论

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

关注公众号