[Tutor] How to Terminate a Popen call?

SM sunithanc at gmail.com
Wed Oct 23 03:04:57 CEST 2013


Hello!
I am trying to terminate a Popen session using Popen.terminate() ( using
the info at http://docs.python.org/library/subprocess.html and some
relevant answers from Stack Overflow). But it doesn't seem to work for me.

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.
Here is the code snippet:

class thread1(threading.Thread):
    def __init__(self, ....):
        ...
        ...
        super(bcThread_allrep_all, self).__init__()
        self.stoprequest = threading.Event()
        self.process = None


    def stopped(self):
        return self.stoprequest.isSet()

    def run(self):
        (process, err) = Popen(self.fwcmd, stdout=PIPE,
stderr=PIPE).communicate()        if len(err) >  0:
            # print("Error")
            # Error handling code
        else:
            # print("Success")

    def stop(self):
        if self.process is not None:
            print("TERMINATING THREAD")
            self.process.terminate()
            #Popen.terminate(self.process)
        else:
            print("process IS NONE ")


>From thread2 I am invoking thread1.stop() method, in order to terminate
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.

The python.org document suggests to use Popen.terminate() call.
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):

  File "bc_reports_tab.py", line 1733, in stop
    Popen.terminate(self.process)
  File "/usr/lib/python3.2/subprocess.py", line 1581, in terminate
    self.send_signal(signal.SIGTERM)
  AttributeError: 'NoneType' object has no attribute 'send_signal'

So how would I terminate Popen before it has finished executing??

Appreciate any help.
Thanks!
-Sm
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131022/b8a68c32/attachment.html>


More information about the Tutor mailing list