多进程进程的输出的非阻塞重定向
我昨天问了一个关于我用 Python 编写的程序的问题( 传递 wxPython对象作为多处理器参数)。我通过对评估脚本的函数使用多进程进程来解决这个问题。但是,由于脚本是从不同的进程运行的,因此它们的输出没有正确重定向到我的 wxPython TextCtrl 窗口。因此,我正在寻找方法将子进程的输出持续重定向到我的主进程,以便可以将其写入我的文本窗口。
这是设置进程的函数:
def createprocess(test):
q = Queue()
q.put(test)
p = Process(target=runtest, args=(q,))
p.start()
p.join()
return q.get()
这是进程的目标函数:
def runtest(q):
test = q.get()
exec 'import ' + test
func=test+'.'+test+'()'
ret = eval(func)
q.put(ret)
我找到了这个线程( 如何将 python 多处理进程输出发送到 Tkinter gui ),它描述了如何重定向子进程的输出,但问题是输出是后收到评估已完成。
I asked a question yesterday about a problem with a program I'm writing in Python ( Passing wxPython objects as multiprocessor arguments ). I managed to solve that problem by using a multiprocess process for the function that evaluates the scripts. However, since the scripts are runned from a different process, their output is not properly redirected to my wxPython TextCtrl window. So, I'm looking for way to continously redirect the output from the childprocess to my main process so it can be written to my text window.
This is the function that sets up the process:
def createprocess(test):
q = Queue()
q.put(test)
p = Process(target=runtest, args=(q,))
p.start()
p.join()
return q.get()
This is the target function of the process:
def runtest(q):
test = q.get()
exec 'import ' + test
func=test+'.'+test+'()'
ret = eval(func)
q.put(ret)
I found this thread ( How can I send python multiprocessing Process output to a Tkinter gui ) which describes how to redirect output from the childprocess but the problem was that the output was received after the evaluation was complete.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决当前问题的方法是使用两个 Queue.Queue 而不是仅一个。我们将它们称为
inqueue
和outqueue
。然后更大的问题涉及如何使用单独进程的输出来控制 GUI 元素(例如 TextCtrl)。答案是你不知道。相反,生成一个线程(如果您愿意,也可以生成其他进程),该线程可以从
outqueue
接收值,并(与单独的进程不同)更新TextCtrl
。有关如何设置的示例,请参阅 LongRunningTasks wiki。
The solution to your immediate problem is to use two
Queue.Queue
s instead of just one. Let's call theminqueue
andoutqueue
. ThenThe larger issue concerns how to control GUI elements like the
TextCtrl
with the output from a separate process. The answer is you don't. Instead spawn a thread (which can if you like spawn other processes), which can receive the values fromoutqueue
and (unlike separate processes) update theTextCtrl
.See the LongRunningTasks wiki for examples on how to set this up.