如何在不同线程中循环运行另一个进程
我正在创建一个图形用户界面应用程序(wxPython)。我需要从这个应用程序中运行另一个(.exe)程序。这个子进程会根据用户的操作执行一些任务,并将结果返回给图形界面应用。
我在一个循环中运行这个子进程,这样它就能随时准备好执行。我做的是启动一个线程(这样图形界面就不会卡住),然后在循环中使用popen来启动子进程。不过,我不太确定这样做是否是最好的方法。
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
现在的问题是,如果主应用程序关闭了,那个线程仍然在等待用户的操作,但这个操作其实不会再来了。我该如何优雅地退出呢?即使图形界面应用已经关闭,application.exe 进程在进程列表中仍然可以看到。欢迎任何改进建议。
谢谢
1 个回答
2
1) 把'proc'变成一个实例属性,这样你就可以在退出之前调用它的terminate()或kill()方法。
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) 使用某个变量来告诉线程停止(你需要在一个循环中使用poll(),而不是用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() is None or not self.exit:
pass
data = ""
while True:
if self.exit:
break
txt = proc.stdout.readline()
data = txt[5:].strip()
txt += data
'atexit'模块的文档可以帮助你在退出时调用一些东西。