在睡眠时杀死python进程
我有一些python文件,它被设置为睡眠一段时间,然后终止某个进程。 但若用户改变主意并想终止我的python程序,他必须转到系统监视器。,因为实例正在休眠在睡眠时杀死python进程,python,linux,subprocess,Python,Linux,Subprocess,我有一些python文件,它被设置为睡眠一段时间,然后终止某个进程。 但若用户改变主意并想终止我的python程序,他必须转到系统监视器。,因为实例正在休眠 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" p
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()
我知道,如果用户愿意,我必须创建另一个进程来杀死这个沉睡的进程,但我不明白怎么做。请提供帮助在命令行环境中,您可以使用以下命令中断脚本:
$python-c'导入时间;时间。睡眠(300)'
^CTraceback(最近一次通话最后一次):
文件“”,第1行,在
键盘中断
按住CTRL+C键,即使在mac上也会关闭进程。如果您讨厌此错误消息,请尝试此代码
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
上述代码适用于2.4-3.10
希望有帮助;D
子进程调用(['pkill',gedit'])
而不是pgrep
我让我的文件可供用户执行。他用doube click来运行它。没有终点站。另外,谢谢你,船长:)@Feanor:你可以用一个“取消”按钮向GUI显示,例如。,
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