所以我有一个 python 脚本,它运行一个循环,在该循环中它通过 subprocess.Popen 调用程序 A 等待其输出,然后保存输出,然后再次调用它,依此类推。 (在我设置为输入的多次运行中,这种情况不断发生)
问题是我有一个计时器,这样只要程序 A 花费的时间超过特定阈值时间,脚本就会使用 process.kill() 终止进程并进入下一次迭代。
问题是,即使运行 300 次似乎一切都工作正常,但有时我会收到此错误:
File "C:\Python27\lib\subprocess.py", line 1002, in terminate
_subprocess.TerminateProcess(self._handle, 1)
WindowsError: [Error 5] Access is denied
然后脚本就死了。
引用的脚本部分:
timeout = TIME_CONST
for run in runs:
killed = False
start = time.clock()
p = subprocess.Popen("SOME.CMD", cwd=r"some_dir")
# Monitor process. If it hits threshold, kill it and go to the next run
while p.poll() is None:
time.sleep(20)
secs_passed = time.clock() - start
### the following was my initial buggy line ###
#if secs_passed >= timeout:
### corrected line after jedislight's answer ###
#if the time is over the threshold and process is still running, kill it
if secs_passed >= timeout and p.poll is None:
p.kill()
killed = True
break
if killed: continue
您对问题可能是什么有什么建议吗?
EDIT:接受答案并修复了代码。感谢@jedislight 的反馈!
您将 p.poll() 和 p.kill() 分开 20 秒。到那时该过程可能已经完成。我建议移动 time.sleep(20) 调用,以便轮询和终止在同一时间范围内发生,以避免杀死死进程。下面是在 iPython 中运行的示例,在终止已完成的进程时显示类似的错误:
In [2]: import subprocess
In [3]: p = subprocess.Popen("dir")
In [4]: p.poll()
Out[4]: 0
In [5]: p.kill()
---------------------------------------------------------------------------
WindowsError Traceback (most recent call last)
C:\Users\---\<ipython console> in <module>()
C:\Python26\lib\subprocess.pyc in terminate(self)
947 """Terminates the process
948 """
--> 949 _subprocess.TerminateProcess(self._handle, 1)
950
951 kill = terminate
WindowsError: [Error 5] Access is denied
即使您在显示进程正在运行的轮询后直接终止,它也可以在执行下一行之前完成。我还建议为此异常添加一个 try-catch 块,如果发生则再次轮询以查看该过程是否实际完成。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)