2016-04-14 77 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。