0

How to nicely shutdown a python program?

I am writing a worker that gets elements from a queue to process them. I'd like to make sure it will wait to finish to process the current item before stoping.

I am not asking for a solution on the queue part. I'm wondering how I can catch the "exit"/"stop" signal coming from outside the python program if I do Ctrl+C or kill.

Thanks

Michael
  • 8,357
  • 20
  • 58
  • 86
  • and what have you tried? what libraries are you using? – Rafael Barros Nov 06 '14 at 22:46
  • We will need details. – Havenard Nov 06 '14 at 22:46
  • Say please? :-) No but seriously, you need to provide a bit more info than this, both about what you want and also what you've tried. It's not really clear from what you have here – Evan Volgas Nov 06 '14 at 22:50
  • I am not asking for a solution on the queue part. I'm wondering how I can catch the "exit"/"stop" signal coming from outside the python program if I do Ctrl+C or kill. I just explained the context of a worker and a queue but that is not the part I want to know since I know it depends on the queue you use, etc – Michael Nov 06 '14 at 22:53

1 Answers1

0

Set a finish flag externally, after each item is processed check the flag before getting the next item off the queue, if it is set exit.

You can trap the exit signals with signal an example is in this SO Question & Answer or you can atexit.register to register a function that will gracefully finish your processing.

A lot depends how you structure the rest of your code - if you are using worker threads/subprocess/multiprocess then atexit is probably the way to go, if you are doing all your work in main then signal will probably work better for you.

Community
  • 1
  • 1
Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
  • Ok but how can I catch the exit signal coming from outside the program? For example, if I do Ctrl+C or kill? – Michael Nov 06 '14 at 23:15
  • Outside the task rather than outside the program - so if you have a gui and several threads doing the processing you have a stop button ... – Steve Barnes Nov 06 '14 at 23:49