python - How to run another process in a loop on a different thread -
i creating gui application(wxpython). need run (.exe) application gui application. subprocess perform operation on user action , return output gui application
i running subprocess in loop, subprocess available execute. doing is, start thread(so gui not freeze) , popen subprocess in loop. not sure if best way.
self.thread = threading.thread(target=self.run, args=()) self.thread.setdaemon(true) self.thread.start() def run(self): while self.is_listening: cmd = ['application.exe'] proc = subprocess.popen(cmd, stdout=subprocess.pipe, stderr=subprocess.stdout) proc.wait() data = "" while true: txt = proc.stdout.readline() data = txt[5:].strip() txt += data
now happens is, if main application shutdown, thread still waiting user action never came. how can exit cleanly? application.exe process can still seen in process list, after gui app has exited. suggestions improve whole thing welcome.
thanks
1) make 'proc' instance attribute, can call it's terminate() or kill() methods before exiting.
self.thread = threading.thread(target=self.run, args=()) self.thread.setdaemon(true) self.thread.start() def run(self): while self.is_listening: cmd = ['application.exe'] self.proc = subprocess.popen(cmd, stdout=subprocess.pipe, stderr=subprocess.stdout) self.proc.wait() data = "" while true: txt = self.proc.stdout.readline() data = txt[5:].strip() txt += data
2) use variable tell thread stop (you need use poll() in loop, instead of using wait()).
self.exit = false self.thread = threading.thread(target=self.run, args=()) self.thread.setdaemon(true) self.thread.start() def run(self): while self.is_listening: cmd = ['application.exe'] proc = subprocess.popen(cmd, stdout=subprocess.pipe, stderr=subprocess.stdout) while proc.poll() none or not self.exit: pass data = "" while true: if self.exit: break txt = proc.stdout.readline() data = txt[5:].strip() txt += data
the 'atexit' module documentation can calling things @ exit.
Comments
Post a Comment