简体   繁体   中英

Terminating subprocess in python2.7

I am working on windows 8 x64 system

I am writing a code in which i am using subprocess to execute one lengthy program while execution i fetch output of program and analyse it runtime, for particular criteria

i want to terminate process as soon as criteria is met, i can't be done in program so i want to terminate subprocess from python

my code looks something like this

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

but i get error like this

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

what is cause of this issue? how can i terminate process before completing?

Call .poll() to check whether the process is still running:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM