WindowsError:[错误 5] 尝试终止子进程时拒绝访问(python)

2022-01-18 00:00:00 python subprocess popen

问题描述

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

So I have a python script that runs a loop in which it calls a program A through subprocess.Popen waits for its output, then saves the output and then calls it again and so on. (This keeps happening for a number of runs I set as an input)

问题是我有一个计时器,这样每当程序 A 花费的时间超过特定的阈值时间时,脚本就会使用 process.kill() 终止进程并继续进行下一次迭代.

The thing is that I have a timer so that whenever the program A takes more than a particular threshold_time, the script kills the process with process.kill() and moves on to the next iteration.

问题是,即使运行 300 次似乎一切正常,但有时我会收到此错误:

The problem is that even though everything seems to work fine even for 300 runs, sometimes I get this error:

    File "C:Python27libsubprocess.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   

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

Do you have any suggestions what the problem might be?

接受答案并修复了代码.感谢@jedislight 的反馈!

Accepted answer and fixed the code. Thanks @jedislight for your feedback!


解决方案

您将 p.poll() 和 p.kill() 分开 20 秒.到那时,该过程可能已经完成.我建议移动 time.sleep(20) 调用,以便您在同一时间范围内轮询和杀死,以避免杀死一个死进程.下面是一个在 iPython 中运行的示例,在终止已完成的进程时显示了类似的错误:

You are seperating your p.poll() and your p.kill() by 20 seconds. By then the process could have finished. I would suggest moving the time.sleep(20) call around so that you poll and kill happen in the same time frame, to avoid killing a dead process. Below is an example run in iPython showing a similar error when killing a completed process:

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:Python26libsubprocess.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 块,如果它发生再次轮询以查看该过程是否实际完成.

Even if you kill directly after a poll that shows the processes is running it can finish before the next line is executed. I would also suggest adding a try-catch block for this exception and if it occurs poll again to see if the process actually completed.

相关文章