gpt4 book ai didi

python - Windows错误 : [Error 5] Access is denied when trying to kill a subprocess (python)

转载 作者:太空狗 更新时间:2023-10-29 18:33:05 24 4
gpt4 key购买 nike

所以我有一个运行循环的 python 脚本,在循环中它通过子进程调用程序 A。Popen 等待其输出,然后保存输出,然后再次调用它,依此类推。 (这在我设置为输入的多次运行中不断发生)

问题是我有一个计时器,这样每当程序 A 花费的时间超过特定的 threshold_time 时,脚本就会使用 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

您对问题可能有什么建议吗?

编辑:接受答案并修复代码。感谢@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 block ,如果它发生,再次轮询以查看该过程是否真正完成。

关于python - Windows错误 : [Error 5] Access is denied when trying to kill a subprocess (python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5573257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com