栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python多重处理将子进程的标准输出重定向到Tkinter文本

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python多重处理将子进程的标准输出重定向到Tkinter文本

仍然可以使用队列而不必摆脱所有

print
语句。您可以使用
Process
从属
stdout
重定向来执行此操作。下面的解决方案使用
Queue
子类来模仿
stdout
。然后,该线程由一个线程监视,该线程寻找被泵送到文本小部件中的新文本。

import sysimport timefrom multiprocessing import Processfrom multiprocessing.queues import Queuefrom threading import Threadfrom Tkinter import *# This function takes the text widget and a queue as inputs.# It functions by waiting on new data entering the queue, when it # finds new data it will insert it into the text widget def text_catcher(text_widget,queue):    while True:        text_widget.insert(END, queue.get())# This is a Queue that behaves like stdoutclass StdoutQueue(Queue):    def __init__(self,*args,**kwargs):        Queue.__init__(self,*args,**kwargs)    def write(self,msg):        self.put(msg)    def flush(self):        sys.__stdout__.flush()def test_child(q):    # This line only redirects stdout inside the current process     sys.stdout = q    # or sys.stdout = sys.__stdout__ if you want to print the child to the terminal    print 'child running'def test_parent(q):    # Again this only redirects inside the current (main) process    # commenting this like out will cause only the child to write to the widget     sys.stdout = qprint 'parent running'    time.sleep(0.5)    Process(target=test_child,args=(q,)).start()if __name__ == '__main__':    gui_root = Tk()    gui_txt = Text(gui_root)    gui_txt.pack()    q = StdoutQueue()    gui_btn = Button(gui_root, text='Test', command=lambda:test_parent(q),)    gui_btn.pack()    # Instantiate and start the text monitor    monitor = Thread(target=text_catcher,args=(gui_txt,q))    monitor.daemon = True    monitor.start()    gui_root.mainloop()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/398415.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号