<div dir="ltr"><div><div><div>Hello!<br></div>I am trying to terminate a Popen session using Popen.terminate() ( using the info at <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">http://docs.python.org/library/subprocess.html</a> and some relevant answers from Stack Overflow). But it doesn't seem to work for me. <br>
<br>I am calling Popen to run a command (which runs for a long time) from one thread (thread1) and trying to stop the execution from another thread (thread2) which is running in a loop. In response to a pushButton, the second thread (thread2) invokes the stop method of the first thread which in turn, invokes the terminate() call.<br>
Here is the code snippet:<br><br>class thread1(threading.Thread):<br>    def __init__(self, ....):<br>        ...<br>        ...<br>        super(bcThread_allrep_all, self).__init__()<br>        self.stoprequest = threading.Event()<br>
        self.process = None<br><br><br>    def stopped(self):<br>        return self.stoprequest.isSet()<br><br>    def run(self):<br>        (process, err) = Popen(self.fwcmd, stdout=PIPE, stderr=PIPE).communicate()        if len(err) >  0:<br>
            # print("Error")<br>            # Error handling code<br>        else:<br>            # print("Success")<br><br>    def stop(self):<br>        if self.process is not None:<br>            print("TERMINATING THREAD")<br>
            self.process.terminate()<br>            #Popen.terminate(self.process)<br>        else:<br>            print("process IS NONE ")<br><br><br>From thread2 I am invoking thread1.stop() method, in order to terminate<br>
the Popen call. So thread1.stop() is getting invoked, but I see that self.process (which is the value Popen has to return) will have "None" before it finishes. <br><br>The <a href="http://python.org">python.org</a> document suggests to use Popen.terminate() call.<br>
So I also tried calling Popen.terminate (as in the commented line above),  but it returns the following error (due to the same reason that self.process is None):<br><br>  File "bc_reports_tab.py", line 1733, in stop<br>
    Popen.terminate(self.process)<br>  File "/usr/lib/python3.2/subprocess.py", line 1581, in terminate<br>    self.send_signal(signal.SIGTERM)<br>  AttributeError: 'NoneType' object has no attribute 'send_signal'<br>
<br>So how would I terminate Popen before it has finished executing??<br><br>Appreciate any help.<br></div>Thanks!<br></div>-Sm<br></div>