python - 如何在不同线程上循环运行另一个进程

标签 python multithreading user-interface wxpython subprocess

我正在创建一个 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 进程仍然可以在进程列表中看到。欢迎提出任何改进整个事情的建议。

谢谢

最佳答案

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

关于python - 如何在不同线程上循环运行另一个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5093446/

相关文章:

jquery - 无法在 django 表单中使用 jquery 更新 choiceField

具有稀疏序列的Python数据结构

c++ - Qt 获取事件文本框

android - 谁能推荐 ICS 的开源号码选择器?

ios - 在 Xcode 的 View 中加载 View Controller

javascript - Django Rest 框架 + ReactJS : Whats wrong with my API?

python - django url 中的 '_' 有什么作用?

java - 在 updateProgress 期间将文本附加到 JavaFX TextArea

java - 哪些变量是线程安全的?

javascript - JavaScript 线程和 Silverlight UI 线程之间是什么关系?