Windows的execfile调用函数超时? (信号替代?)

时间:2013-10-29 09:52:47

标签: python python-2.7 timeout execfile

就像标题所说的那样,我正在尝试运行一些execfile调用,但我正在寻找一个超时选项,这样如果我的被调用脚本需要超过十秒才能运行,那么它将终止被调用的脚本并继续......

信号库/包仅适用于UNIX,我在Windows上,所以我有点卡住了。

# Sequential wait to finish before moving onto the next script
try: 
    execfile("SUBSCRIPTS/TESTSCRIPT.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

# Semi-Sequential (Don't wait for it to finish before moving onto the third script)
subprocess.Popen(["pythonw", "SUBSCRIPTS/TEST.py", "0"], shell=True)

# Sequential wait to finish before moving onto the next script
try: 
    execfile("SUBSCRIPTS/TEST.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

# Sequential wait to finish before moving onto the next script
try: 
    execfile("SUBSCRIPTS/TESTSCRIPT.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

这样的事情应该有效:

# Sequential wait to finish before moving onto the next script
try: 
    execfile("SUBSCRIPTS/TESTSCRIPT.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

# Semi-Sequential (Don't wait for it to finish before moving onto the third script)
p1 = subprocess.Popen(["pythonw", "SUBSCRIPTS/TEST.py", "0"], shell=True)

# Sequential wait to finish before moving onto the next script
try: 
    execfile("SUBSCRIPTS/TEST.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

#Do you want to kill the "pythonw", "SUBSCRIPTS/TEST.py", "0" command after the "SUBSCRIPTS/TEST.py" call or do you want to allow the pythonw command to continue running until after the "SUBSCRIPTS/TESTSCRIPT.py"

#you need to put this code depending on where the subprocess.Popen(["pythonw", "SUBSCRIPTS/TEST.py", "0"], shell=True) #script needs to be killed
currentStatus = p1.poll()
if currentStatus is None: #then it is still running
  try:
    p1.kill() #maybe try os.kill(p1.pid,2) if p1.kill does not work
  except:
    #do something else if process is done running - maybe do nothing?
    pass

# Sequential wait to finish before moving onto the next script
try: 
    execfile("SUBSCRIPTS/TESTSCRIPT.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

#or put the code snippet here if you want to allow the pythonw command to continue running until after the SUBSCRIPTS/TESTSCRIPT.py command

取值