我有一个全天运行的 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 将无限期运行。这就是为什么我需要能够在它仍在运行的某个时间“强制”杀死它。
有什么线索吗?我究竟做错了什么?如何杀死它?
请您参考如下方法:
你正在杀死产生你的子进程的 shell,而不是你的子进程。
编辑:来自文档:
您唯一需要在 Windows 上指定 shell=True 的情况是当您希望执行的命令内置于 shell 中时(例如 dir 或 copy)。您不需要 shell=True 来运行批处理文件或基于控制台的可执行文件。
警告
如果结合不受信任的输入,传递 shell=True 可能会带来安全隐患。有关详细信息,请参阅常用参数下的警告。
因此,与其传递单个字符串,不如分别传递列表中的每个参数,并避免使用 shell。您可能希望为子项和父项使用相同的可执行文件,因此通常是这样的:
pro = subprocess.Popen([sys.executable, "python-task.py"])
