Reputation: 2998
I have a program that requires some cleaning up after exiting, and have written a seperate .py file for this. However, the program I use stays in an infinite loop at one part:
pythoncom.PumpMessages()
Because of this, there is no "natural" closing of the program. The only way is to end the process from task manager.
So I ask: is there a way to, upon being ended from task manager, to run my clean up python script automatically?
Edit: I could put it in an infinite loop in a different way, such as this, if it helps:
while True:
pythoncom.PumpWaitingMessages()
Upvotes: 1
Views: 244
Reputation: 3514
There is sample from my project:
import signal
def term(*args,**kwargs):
sys.stderr.write('\nStopping...')
do_cleaning_stuff_here()
signal.signal(signal.SIGTERM, term)
signal.signal(signal.SIGINT, term)
signal.signal(signal.SIGQUIT, term)
yuor_main_code_here()
With infinite loop:
import signal
def term(*args,**kwargs):
global running
sys.stderr.write('\nStopping...')
running=False
signal.signal(signal.SIGTERM, term)
signal.signal(signal.SIGINT, term)
signal.signal(signal.SIGQUIT, term)
running=True
while running:
handle()
cleanup()
windows signals translated to unix equivalent.
Upvotes: 3
Reputation: 2828
You can run both scripts from a separate python script and kill the first process before running the second.
For example using subprocess.Popen:
proc1 = subprocess.Popen(cmd, shell = True)
time.sleep(waititme) #or other flag, such as reading another source
proc1.kill()
proc2 = subprocess.Popen(cmd2, shell = True)
Upvotes: 3
Reputation: 5864
In unix, when you kill a process, you send it a signal. For example, CTRL-C causes a signal sent to the program.
On windows, some of these signals are emulated, including CTRL-C. If your loop isn't calling functions that block the CTRL-C signal, then you can press CTRL-C to kill the loop. Could you try terminating your program with CTRL-C instead of doing it through the task manager?
If it works that way, you can write a handler to catch the CTRL-C signal, cleanup the program state, and sys.exit()
.
Here is code to capture the signal: How do I capture SIGINT in Python?
Upvotes: 1