WindowsError: [Error 5] Access is denied when trying to kill a subprocess (python)

前端 未结 1 983
青春惊慌失措
青春惊慌失措 2021-01-02 06:03

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

相关标签:
1条回答
  • 2021-01-02 06:41

    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:\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
    

    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.

    0 讨论(0)
提交回复
热议问题