Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在睡眠时杀死python进程_Python_Linux_Subprocess - Fatal编程技术网

在睡眠时杀死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

我有一些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" 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