【问题标题】:Terminating subprocess in python2.7在python2.7中终止子进程
【发布时间】:2013-05-19 15:05:48
【问题描述】:

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

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

【问题讨论】:

  • if criteria_met: 块中应该有break

标签: python multithreading python-2.7 multiprocessing subprocess


【解决方案1】:

调用.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

【讨论】:

    猜你喜欢
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多