python - 从 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
解决方案
您可以使用Queue
(https://docs.python.org/3/library/queue.html)在线程之间传递值,因此将队列传递给您的守护线程,将 pid 放入队列并在主线程中检索它。
推荐阅读
- saucelabs - 尝试将 .ipa 文件上传到 saucelabs 时出错
- powershell - Get-ADPrincipalGroupmembership :由于内部错误,服务器无法处理请求
- sql - CSLA 生成的 SQL
- ffmpeg - ffmpeg AVStream::codecpar 为空
- windows - Cassandra 作为 Windows 服务无法启动
- angular - 在 Angular 中工作时丢失了 localhost:4200 中的内容
- html - 将信息连接到输入
- java - 运行 Android 10 的三星手机不显示录制的视频
- javascript - 避免下拉列表中的多个事件:ReactJS
- python - Django重置密码链接给出404