Friday, 23 April 2021

How to terminate a thread subprocess call and thread exit in python?

I am trying to run subprocess Popen in a thread in Python. The command in Popen is expected to run continously to collect logs. But when a condition is met outside the thread, I want to stop the Popen subprocess and the corresponding thread also to finish. Below is a sample representative code:

import threading
import subprocess

class MyClass(threading.Thread):
    def __init__(self):
        super(MyClass, self).__init__()
    
    def run(self):
        self.proc = subprocess.Popen("while true; do foo; sleep 2; done", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = self.proc.communicate()
            
myclass = MyClass()
myclass.start()

myclass.proc.kill()



print("Done")

But in the above code, it stucks forever. What would be the correct way to stop the running Popen subprocess and also to finish the thread?



from How to terminate a thread subprocess call and thread exit in python?

No comments:

Post a Comment