如何在不同线程的循环中运行另一个进程

问题描述:

我正在创建一个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进程。任何改善整个事情的建议都是值得欢迎的。

感谢

+2

为什么不使用'wx.Process' /'wx.Execute()'? – 2011-02-23 16:19:12

1)制作“PROC”一个实例属性,这样你就可以调用它的终止()或中止()退出之前的方法。

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' module documentation可以帮助您在退出调用的东西。