Killing sub process that run inside a thread


I'm using python 3.5.3 with PyQT 5 and I have written GUI with it. This GUI run python code python code with subprocess.run.

In order to leave my GUI active and not frozen during the subprocess operation , i'm running the subprocess in a thread.

In the GUI i have stop button that if the user pressed , I want to terminate the subprocess.

I have no problem to kill the thread by using terminate method of the thread. But that's don't terminate the subprocess.

I've tried to use Popen instead of run but I cant make it to run as subprocess.run does. in addition , I prefer to use the recommended way by Python that's give me also the check_error option

This is how I use subprocess:

class c_run_test_thread(QtCore.QThread): def __init__(self,test_file,log_file): QtCore.QThread.__init__(self) self.test_file = test_file self.log_file = log_file def __del__(self): self.wait() def run(self): # Thread logic try: # Run the test with all prints and exceptions go to global log file self.test_sub_process = subprocess.run(["python", self.test_file],stdout = self.log_file, stderr = self.log_file,check = True) except subprocess.CalledProcessError as error: print("Error : {}".format(error)) # Flush memory to file self.log_file.flush( def stop(self): # Flush memory to file self.log_file.flush()

And I terminate the thread by

# Stop test thread self.thread_run_test.terminate()

To sum things up , I want to kill thread while killing its sub process too.


There may be other simpler ways to this, but what I did was to

<ol><li>Use subprocess.Popen to run a sub process, instead of subprocess.run, since the latter will not return before the process is terminated</li> <li>Check if the process is terminated using Popen.poll</li> <li>Kill the process using Popen.kill</li> </ol>

A sample code would be sth. like the following:

self.test_sub_process = subprocess.Popen(["python", self.test_file], stdout=self.log_file, stderr=self.log_file)

Wait for termination:

print("Return code: {}".format(self.test_sub_process.wait()))

Or if you want to do something while waiting:

while self.test_sub_process.poll() is None: doSomething() print("Return code: {}".format(self.test_sub_process.poll()))

Then in thread_run_test.terminate(), you can kill the process




  • How to prevent showing/receiving untranslated content?
  • Extract IP address from HTML document
  • Bit Shift Large Binary File?
  • Cloudflare and Firebase
  • Dynamic width for report in ireport 4.0.1
  • Knockout/Select2: Triggering select2 to update based on an observable option updating
  • Difference between applying async-await at client and at service
  • `cleartool lsco -r -cvi -me` is extremely slow compared to `cleartool lsco -graphical`. Is it possib
  • How to fork and exec a server and wait until it's ready?
  • Is there any kind of jQuery.browser fallback?
  • Is there a way to query who are activesync/bb users through Exchange PowerShell?
  • Excel Vba - Using an apostrophe in an sql string
  • Hibernate query filter on collection
  • Per Machine App Registration
  • Merging a large number of files from one directory into a data frame in R
  • Unknown C# type
  • Should a C# struct have only read-only properties
  • subprocess.Popen('start') fails
  • Whats the best way of persisting data to Isolated Storage on Windows Phone 7?
  • What version of Java should I use with Cassandra 2.0?
  • Zend Framework + Doctrine1.2 project structure with more modules
  • Is it better to use the “hidden” CSS attribute or fetch each set of new images?
  • File extension of zlib zipped html page?
  • import scipy.sparse failed
  • During installation of Django, why do I keep getting ImportError: No module named django?
  • where do I find the xml.dom python package for the python-2.6.0-8.9.28 and I have a suse/x86_64 vers
  • Python pickle not one-to-one: different pickles give same object
  • Python CGI os.system causing malformed header
  • Linq Objects Group By & Sum
  • Optimizing database types to compact database (SQLite)
  • HTML download movie download link
  • Buffer size for converting unsigned long to string
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • Java static initializers and reflection
  • unknown Exception android
  • Programmatically clearing map cache
  • reshape alternating columns in less time and using less memory
  • Observable and ngFor in Angular 2
  • Unable to use reactive element in my shiny app