Python:在多线程应用程序中为每个线程打印到单独的 bash 行

Vin*_*oft 5 python multithreading

我在这篇文章中看到,很容易通过以下方式在同一行上打印(覆盖以前的内容):

print "Downloading " + str(a) " file of " + str(total),
Run Code Online (Sandbox Code Playgroud)

(注意末尾的逗号)。这会导致

>>> Downloading 1 file of 20
Run Code Online (Sandbox Code Playgroud)

每次执行打印时,都会更新同一行。

这在单线程应用程序中效果很好,但不适用于多线程。

在 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
Run Code Online (Sandbox Code Playgroud)

Ton*_*ino 5

您可以使用curses模块来实现这一点。

curses 模块提供了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()
Run Code Online (Sandbox Code Playgroud)