在python2.7中终止子进程

时间:2013-05-19 15:05:48

标签: python multithreading python-2.7 multiprocessing subprocess

我正在使用Windows 8 x64系统

我正在编写一个代码,我在其中使用子进程来执行一个冗长的程序 执行时我获取程序的输出并分析它的运行时间,特别是标准

我希望在符合条件后立即终止进程,我无法在程序中完成,所以我想从python终止子进程

我的代码看起来像这样

class myThread (threading.Thread):
    def __init__(self, threadI....
        ........
        .......

    def run(self):
        self.process= subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        for line in iter(p.stdout.readline, b''):
            .........................
            ......Run-time Analysis........
            .........................
            if (criteria_met):
                  self.stop()
            .........................
            ........................
    def stop(self):
    if self.process is not None:
        self.process.terminate()
        self.process = None

但我得到这样的错误

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 551, in __bootstrap_inner
    self.run()
  File "VB_Extraction.py", line 57, in run
    self.process.kill()
  File "C:\Python27\lib\subprocess.py", line 1019, in terminate
    _subprocess.TerminateProcess(self._handle, 1)
WindowsError: [Error 5] Access is denied

这个问题的原因是什么? 如何在完成前终止流程?

1 个答案:

答案 0 :(得分:0)

调用.poll()检查进程是否仍在运行:

if self.process is not None and self.process.poll() is None: # still running
    self.process.terminate() # or .kill() if it doesn't terminate it
    self.process.communicate() # close pipes, wait for completion
    self.process = None