2012-07-12 95 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可以做所有這些,並且應該返回兩個字符串緩衝區作爲元組。

相關問題