2012-07-12 28 views
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打印输出在两个不同的字符串,以便我可以使用,以显示他们在两个不同的标签我的GUI。重定向线程的输出到一个字符串在Python

另外,我尝试使用StringIO(),但由于它们是并行运行的线程,所以输出顺序显然搞砸了。我正在学习使用子过程的东西,但不知道如何......仍在尝试。

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

回答

1

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

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

+0

使用它变得复杂。不过,这个想法很好。为了我的需要,我的答案中的代码很好。 – VoodooChild92 2012-07-12 12:21:04

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变量包含来自函数“杜朋”和“循环”的打印输出。

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

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

0

我试过使用StringIO(),但是因为它们是并行运行的线程,输出序列显然搞砸了。

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

相关问题