首页 > 解决方案 > 从 Thread 创建的子进程中获取进程 ID

问题描述

我有一个使用 GUI 的简单 python 应用程序。在那个 GUI 上,我有一个“开始”按钮:

gui.py
self.button_start = tk.Button(master=self.frame_button_start, text="Start",
                                      command=self.controler.start(target=Writer.start_server()), width=20)

如您所见,它start(self, target=None)从我的自定义类中调用该函数Controler

Controler是一个管理创建的类,Thread函数start如下所示:

#controler.py
def start(self, target):
    self.current_thread = Thread(target=target, daemon=True)
    self.current_thread_list.append(self.current_thread)
    sikuli_process_id = self.current_thread

使用开始按钮,它创建一个Thread执行启动一个函数的函数subprocess

# writer.py
def start_server():
    dirpath = os.getcwd()
    rootpath = dirpath[:-6]
    sikulixjar = rootpath + 'sikulix\sikulix.jar'
    group_file = rootpath + 'sikulix\groups.txt'
    now = time.strftime('%Y%m%d%H%M%S')
    logfilename = now + '-server.log'
    userlog = rootpath + 'Writer\\Logs\\User\\' + logfilename
    logfile = rootpath + 'Writer\\Logs\\System\\' + logfilename
    """Start the server in an asynch subprocess by executing the java command that execute sikuli"""
    javacommand = 'java -jar {} -d 2 -f {} -u {} -g {} -s'.format(sikulixjar, logfile, userlog, group_file)
    print("### STARTING SERVER ###")
    server = subprocess.Popen(javacommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                              shell=True, universal_newlines=True)
    Controler.Controler.output_manager()
    return server.pid

我现在问自己是否有可能server.pid返回到gui.py,我不知道如何start_server() 从线程中获取返回值。

我的项目如下所示:

-root - classes - controler.py
      |         | gui.py
      |
      - functions - writer.py

标签: pythonpython-3.xmultithreadingsubprocess

解决方案


您可以使用Queuehttps://docs.python.org/3/library/queue.html)在线程之间传递值,因此将队列传递给您的守护线程,将 pid 放入队列并在主线程中检索它。


推荐阅读