0

我正在使用 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

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

4

1 回答 1

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
于 2013-05-19T18:44:54.127 回答