无法在Windows上使用Python终止正在运行的子进程

2024-04-26 10:42:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python脚本,它每60秒运行一整天的检查时间,这样它就可以在一天中的特定时段开始/结束任务(其他Python脚本)。在

这个脚本运行得几乎一切正常。任务在正确的时间开始,并在新的cmd窗口中打开,因此主脚本可以继续运行并采样时间。唯一的问题是它不会扼杀任务。在

import os
import time
import signal
import subprocess
import ctypes


freq = 60 # sampling frequency in seconds

while True:    
    print 'Sampling time...'
    now = int(time.time())

    #initialize the task.. lets say 8:30am
    if ( time.strftime("%H:%M", time.localtime(now)) == '08:30'):
        # The following method is used so python opens another cmd window and keeps original script running and sampling time 
        pro = subprocess.Popen(["start", "cmd", "/k", "python python-task.py"], shell=True)

    # kill process attempts.. lets say 11:40am
    if ( time.strftime("%H:%M", time.localtime(now)) == '11:40'):
        pro.kill()    #not working - nothing happens

        pro.terminate()    #not working - nothing happens

        os.kill(pro.pid, signal.SIGINT) #not working - windows error 5 access denied

        # Kill the process using ctypes - not working - nothing happens
        ctypes.windll.kernel32.TerminateProcess(int(pro._handle), -1)

        # Kill process using windows taskkill - nothing happens
        os.popen('TASKKILL /PID '+str(pro.pid)+' /F')

    time.sleep(freq)

重要提示:任务脚本python-task.py将无限期运行。这正是为什么我需要能够在它还在运行的时候“强迫”杀死它。在

有什么线索吗?我做错什么了?怎么杀了它?在


Tags: import脚本cmdtasktimeos时间not
1条回答
网友
1楼 · 发布于 2024-04-26 10:42:17

您正在杀死生成子进程的shell,而不是子进程。在

编辑:来自文档:

在Windows上,唯一需要指定shell=True的时间是将要执行的命令内置到shell中时(例如dir或copy)。运行批处理文件或基于控制台的可执行文件不需要shell=True。在

警告

如果与不受信任的输入结合使用,传递shell=True可能会带来安全隐患。有关详细信息,请参阅“常用参数”下的警告。在

因此,不要传递单个字符串,而是在列表中分别传递每个参数,并避免使用shell。您可能希望为子级和父级使用相同的可执行文件,因此通常如下所示:

pro = subprocess.Popen([sys.executable, "python-task.py"])

相关问题 更多 >