【问题标题】:Redirect a thread's output to a string in python将线程的输出重定向到python中的字符串
【发布时间】:2012-07-12 06:23:35
【问题描述】:
def findStats():
     thread1 = thread.start_new_thread(func1, (arg_1, arg_2))
     thread2 = thread.start_new_thread(func2, (arg_3, arg_4))

def func1(arg_1, arg_2):
     """
        Some code which prints some stuff
     """

def func2(arg_3, arg_4):
     """ 
        Some code which prints some other stuff
     """

在这里,我想做的是在两个单独的字符串中捕获来自 func1 和 func2 的打印输出,以便我可以使用 in 在我的 GUI 的两个不同选项卡中显示它们。

另外,我尝试使用 StringIO(),但由于它们是并行运行的线程,输出序列显然是混乱的。我正在学习使用子流程的东西,但不确定如何......仍在尝试。

可以吗?如果是这样,请告诉我一个方法。在此先感谢:)

【问题讨论】:

    标签: python multithreading subprocess


    【解决方案1】:

    使用python的日志模块。 这处理访问的序列化,您可以为每个日志设置级别。 可能需要使用日志标识符对消息进行时间戳记。

    链接这里http://docs.python.org/howto/logging.html

    【讨论】:

    • 使用它变得很复杂。尽管如此,这个想法还是不错的。对于我的需要,我的答案中的代码很好。
    【解决方案2】:
      import sys
      from cStringIO import StringIO
      from multiprocessing import Process, Queue
    
      def mp():
          queue = Queue()
          p = Process(target=loop,args=('lo','op'))
          q = Process(target=doop,args=('do','op'))
          p.start()
          q.start()
          p.join()
          q.join()
    
      def loop(p,x):
          old_stdout = sys.stdout  # Redirection of the printing output to a StringIO
          sys.stdout = mystdout = StringIO()
          for i in xrange(100):
              print p + x
          ### Write the code\functions necessary in here. ###
          sys.stdout = old_stdout
          dataStats_1 = mystdout.getvalue()    # Put all the redirected output into a string.
    
      def doop(q,y):
          old_stdout = sys.stdout   # Redirection of the printing output to a StringIO() 
          sys.stdout = mystdout = StringIO()
          for i in xrange(100):
              print q+y
          ### Write the code\functions necessary in here. ###
          sys.stdout = old_stdout
          dataStats_2 = mystdout.getvalue()                      
    
      if __name__ == "__main__":
          mp()
    

    因此,在每个 dataStats_1 和 dataStats_2 变量中都包含函数“doop”和“循环”的打印输出。

    我不知道上述方法的真实性如何。但这实际上对我有用。

    此外,如果您尝试使用线程而不是进程,则这种将打印输出重定向到 StringIO 的方法将不起作用,因为线程继承父级的 I/O 源并且当您在特定线程中更改它时,它也改变了父线程。但是对于子进程,它不会干扰父进程的 I/O 源。所以,这行得通。

    【讨论】:

      【解决方案3】:

      我尝试使用 StringIO(),但由于它们是并行运行的线程,输出序列显然是混乱的。

      既然你有这个方法,你可以坚持下去:为每个线程将sys.stdout重定向到一个单独的StringIO对象。在创建第一个线程之前重定向一次;然后在创建第二个线程之前重定向到不同的StringIO 对象。您的函数 findStats 可以完成所有这些操作,并且应该将两个字符串缓冲区作为元组返回。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-10
        • 1970-01-01
        • 2013-05-18
        • 2012-02-01
        • 1970-01-01
        • 2019-05-24
        相关资源
        最近更新 更多