2016-04-14 76 views
2

this post看到它很容易在同一行打印(覆蓋先前的內容)的方式如下:的Python:打印到單獨的bash線每個線程,在多線程應用程序

print "Downloading " + str(a) " file of " + str(total), 

(注最後的逗號)。這將導致

>>> Downloading 1 file of 20 

並且每次執行打印時,都會更新同一行。

這適用於單線程應用程序,但它不適用於多線程。

在python 2.7中如何將多個線程打印到自己的終端?

期望的結果會是這個樣子:

>>> Thread 1: Downloading 11 file of 20 
>>> Thread 2: Downloading 4 file of 87 
>>> Thread 3: Downloading 27 file of 32 
>>> Thread 4: Downloading 9 file of 21 

回答

1

可以實現,使用curses module

curses模塊提供了一個到curses庫的接口, 事實上用於便攜式高級終端處理的標準。

每個線程都可以編輯其全局字符串變量,並且可以在主線程中使用curses在單獨的行中顯示這些變量。

檢查我寫的示例代碼,它做什麼,你想:

from threading import Thread 
import curses 
import time 

#global variables 
line_thread_1 = 0 
line_thread_2 = 0 
end_1 = False 
end_2 = False 

def thread1(): 
    global line_thread_1 
    global end_1 
    for i in xrange(10): 
     time.sleep(0.5) 
     line_thread_1 += 1 
    end_1 = True 

def thread2(): 
    global line_thread_2 
    global end_2 
    for i in xrange(10): 
     time.sleep(0.25) 
     line_thread_2 += 1 
    end_1 = True 

thread1 = Thread(target=thread1) 
thread2 = Thread(target=thread2) 
thread1.start() 
thread2.start() 

stdscr = curses.initscr() 
while not (end_1 or end_2): 
    stdscr.erase() 
    stdscr.addstr('>>> Thread 1: ' + str(line_thread_1) + ' of 10\n') 
    stdscr.addstr('>>> Thread 2: ' + str(line_thread_2) + ' of 10\n') 
    stdscr.refresh() 
    time.sleep(1) 
curses.endwin() 
+0

不應該避免在多線程應用程序中使用全局變量嗎? 感謝您的回答,儘管 – Vingtoft

+1

好吧,如果很多線程在相同的全局變量上運行,競態條件可能會發生,並且需要額外的處理 - 例如使用鎖。但在這種簡單的情況下,每個線程都在自己的變量上運行,所以沒有什麼不好的事情會發生 –

1

在該行的末尾逗號只是阻止一個換行符被打印在字符串的結尾。當您再次調用它時,它不會編輯以前打印的行。這與線程無關。看看這個:

print "a ", 
print "b ", 
print "c" 
print "d ", 
print "e ", 
print "f" 

的輸出將是:

a b c 
d e f 

因爲每個有在最後一個逗號的時候,下一個打印的通話將只能像以前一樣添加到同一條線上。

如果你想控制那裏的東西都印也許光標移動可能是有用的: http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html

您還可以,如果你需要更復雜的東西用的library。