简体   繁体   English

在睡眠时杀死python进程

[英]killing python process while sleep

I have some python file, that is made to sleep some time and then terminate some process.我有一些 python 文件,它会休眠一段时间然后终止某个进程。 But if user changed his mind and wants to terminate my python program, he has to go to system monitor.但是如果用户改变主意并想终止我的python程序,他必须转到系统监视器。 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请帮忙

Holding down CTRL+C, even on mac will shut the process down.按住 CTRL+C,即使在 mac 上也会关闭进程。 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.上面的代码适用于 2.4-3.10。

Hope it helped ;D希望它有所帮助;D

In a command-line environment you could interrupt the script using Ctrl+C ( SIGINT ) :在命令行环境中,您可以使用Ctrl+C ( SIGINT )中断脚本:

$ python -c'import time; time.sleep(300)'
^CTraceback (most recent call last):
  File "<string>", line 1, in <module>
KeyboardInterrupt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM