我有一个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将无限期运行。这正是为什么我需要能够在它还在运行的时候“强迫”杀死它。在
有什么线索吗?我做错什么了?怎么杀了它?在