【问题标题】:redirect subprocess log to wxpython txt ctrl将子进程日志重定向到 wxpython txt ctrl
【发布时间】:2011-11-14 15:36:04
【问题描述】:

我想从基于 python 的子进程中捕获日志 o/p。这是我的代码的一部分。我如何将我的日志也重定向到这个 txt ctrl 这是 mytest.py:

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()

我正在我的 maingui 中做这样的事情:

    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") 

在我的 gui 中

    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 ")

【问题讨论】:

    标签: python logging wxpython subprocess


    【解决方案1】:

    您可以尝试按照this post中的建议进行操作。

    更新:您可以将子进程中的记录器设置为使用SocketHandler,并在 GUI 中设置一个套接字服务器以侦听来自子进程的消息,使用链接中的技术-发布以实际使事物出现在 GUI 中。 logging documentation 中包含一个工作的套接字服务器。

    【讨论】:

    • 我试过了,但是在子进程中调用的mytest.py中的日志消息没有显示在txt ctrl中
    • 这似乎可行,但所有日志消息似乎都在 txt ctrl 中一次性更新,因为可能是我在空闲时更新 wx.TextCtrl 但这可能与我的问题没有直接关系顶起来。
    【解决方案2】:

    我写了一篇文章,介绍如何使用 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/

    我还没有尝试使用日志模块进行重定向,但这可能是我将来会做的事情。

    【讨论】:

      猜你喜欢
      • 2018-01-11
      • 2019-01-03
      • 2015-01-01
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      • 2020-04-23
      相关资源
      最近更新 更多