如何在不同线程上循环运行另一个进程
我正在创建一个 GUI 应用程序(wxPython)。我需要从 GUI 应用程序运行另一个 (.exe) 应用程序。子进程将对用户操作执行一些操作,并将输出返回到 GUI 应用程序,
我正在循环中运行此子进程,以便子进程始终可以执行。我正在做的是,我启动一个线程(所以 gui 不会冻结)并打开 循环中的子进程。不确定这是否是最好的方法。
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
现在发生的情况是,如果主应用程序关闭,线程仍在等待从未发生的用户操作。怎样才能干净利落地退出?即使 GUI 应用程序退出后,application.exe 进程仍然可以在进程列表中看到。欢迎提出任何改进整个事情的建议。
谢谢
I am creating a GUI application(wxPython). I need to run another (.exe) application from the GUI application. The subprocess will perform some operation on a user action and return an output to the GUI application
I am running this subprocess in a loop, so that constantly the subprocess is available to execute. What I am doing is, I start a thread(so gui does not freeze) and popen the
subprocess in a loop. Not sure if this is the 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 what happens is, if the main application is shutdown, the thread is still waiting for a user action which never came. How can I exit cleanly? The application.exe process can still be seen in the process list, even after GUI app has exited. Any suggestions to improve the whole thing are welcome.
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1)将“proc”设置为实例属性,这样您就可以在退出之前调用它的terminate()或kill()方法。
2)使用一些变量告诉线程停止(您需要在循环中使用 poll(),而不是使用 wait())。
'atexit' 模块文档< /a> 可以帮助您在退出时调用事物。
1) Make 'proc' a instance attribute, so you can call it's terminate() or kill() methods before exiting.
2) Use some variable to tell the thread to stop (You will need to use poll() in a loop, instead of using wait()).
The 'atexit' module documentation can help you with calling things at exit.