2011-04-06 44 views
9

所以我有一个python脚本运行一个循环,在其中它通过subprocess调用程序A.Popen等待它的输出,然后保存输出,然后再次调用,等等。 (这一直发生在我设置为输入的多次运行中)WindowsError:[错误5]试图杀死一个子进程时,访问被拒绝(python)

事情是,我有一个计时器,以便每当程序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的反馈!

+0

你能发布可以重现此行为的最小Python脚本吗? – 2011-04-07 00:13:32

+0

@Sridhar我添加了你要求的代码。 – Galois 2011-04-08 03:11:26

+0

我试着用“SOME.CMD”只是“CMD”,它的工作。你想要杀死的是什么过程? – Fenikso 2011-04-13 07:27:44

回答

6

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

+0

我认为你是对的。我错过了那部分。感谢您的注意! – Galois 2011-06-04 00:42:31

+0

尝试读取mp3文件时,遇到与librosa/audioread程序包类似的问题。但不幸的是,try-catch技巧对我不起作用 – 2017-07-29 20:32:26

相关问题