0
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() 但由于它们是并行运行的线程,因此输出序列显然是混乱的。我正在学习使用子流程的东西,但不确定如何......仍在尝试。

可以做到吗?如果是这样,请告诉我一个方法。提前致谢 :)

4

3 回答 3

1

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

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

于 2012-07-12T06:46:36.930 回答
0
  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”和“循环”的打印输出。

我不知道上述方法有多真实。但这实际上对我有用。

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

于 2012-07-12T12:26:34.590 回答
0

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

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

于 2012-07-12T18:26:07.963 回答