将子进程日志重定向到wxpython文本控件

1 投票
2 回答
957 浏览
提问于 2025-04-17 06:18

我想从一个基于Python的子进程中获取日志输出。以下是我代码的一部分。我该如何把我的日志也重定向到这个文本控件中呢?

import logging     
log=logging.getLogger('test')    
class MyTestClass():           
    def TestFunction(self) :    
    log.info("start function"
    # runs for 5 - 10 mins and has lots of log statments   
    print "some stuff"      
    log.info("after Test Function")
    # for now
    return a,b    
    #sys.exit(2)    

if __name__ == "__main__":   
  myApp=MyTestClass()  
  myApp.TestFunction()

在我的主界面中,我正在做类似这样的事情:

    class WxLog(logging.Handler):
           def __init__(self, ctrl):
                logging.Handler.__init__(self)
                self.ctrl = ctrl
           def emit(self, record):
                  if self.ctrl:
                        self.ctrl.AppendText(self.format(record)+"\n") 

在我的图形用户界面中

    self.log = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE| wx.TE_RICH2)
    #logging.basicConfig(level=logging.INFO)
    self.logr = logging.getLogger('')
    self.logr.setLevel(logging.INFO)
    hdlr = WxLog(self.log)
    hdlr.setFormatter(logging.Formatter('%(message)s '))
    self.logr.addHandler(hdlr)

    #snip 

    prog = os.path.join(mydir,"mytest.py")
    params = [sys.executable,prog]
    # Start the subprocess
    outmode = subprocess.PIPE
    errmode = subprocess.STDOUT
    self._proc = subprocess.Popen(params,
                                      stdout=outmode,
                                      stderr=errmode,
                                      shell=True
                                     )


    # Read from stdout while there is output from process
    while self._proc.poll() == None:
         txt = self._proc.stdout.readline()
         print txt

    # also direct log to txt ctrl 
    txt =  'Return code was ' + str(self._proc.returncode) +'\n'   

    # direct     
    self.logr.info("On end ")

2 个回答

1

我写了一篇文章,讲的是我怎么用子进程(subprocess)把一些东西,比如ping和traceroute,重定向到我的TextCtrl小部件里。你可以在这里查看:http://www.blog.pythonlibrary.org/2010/06/05/python-running-ping-traceroute-and-more/

这可能会帮助你理解怎么做。还有一篇更通用的文章,没有使用子进程,你可以看看:http://www.blog.pythonlibrary.org/2009/01/01/wxpython-redirecting-stdout-stderr/

我还没有尝试用日志模块(logging module)来重定向,不过这可能是我将来会做的事情。

1

你可以试着按照这篇文章里的建议来做。

更新:你可以在子进程中设置一个记录器,使用SocketHandler,然后在图形界面中建立一个套接字服务器,来监听来自子进程的信息。可以参考链接中的方法,让这些信息在图形界面上显示出来。一个可以工作的套接字服务器的例子在日志文档中有介绍。

撰写回答