Reputation: 3680
I have some python file, that is made to sleep some time and then terminate some process. But if user changed his mind and wants to terminate my python program, he has to go to system monitor. because instance is sleeping.
import subprocess
import os
import signal
import datetime
import time
def kill():
time.sleep(3600) #sleep for 1 hour
#here goes terminating, for example "gedit" process after sleeping
proc = subprocess.Popen(["pgrep", "gedit"], stdout=subprocess.PIPE)
for pid in proc.stdout:
os.kill(int(pid), signal.SIGTERM)
if __name__ == "__main__":
kill()
I know i have to create another process to kill this sleeping one if user wants, but i can't understand how. Help please
Upvotes: 2
Views: 1943
Reputation: 655
Holding down CTRL+C, even on mac will shut the process down. If you hate the error message, try this code.
from time import sleep
try: #Try to do this
sleep(3600) #One hour sleep
'''vvv Your code goes here vvv'''
'''^^^^^^^^^^^^^^^^^^^^^^^^^^^'''
except KeyboardInterrupt: #In the case of keyboard interrupt
exit() #Kill process, end code, no errors, except that you will see ^C upon keyboard interrupt. This is also Ctrl+C on mac.
#EOF
Code above works with 2.4-3.10.
Hope it helped ;D
Upvotes: 2
Reputation: 414079
In a command-line environment you could interrupt the script using Ctrl+C (SIGINT
):
$ python -c'import time; time.sleep(300)'
^CTraceback (most recent call last):
File "<string>", line 1, in <module>
KeyboardInterrupt
Upvotes: 1