gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:58:49 25 4
gpt4 key购买 nike

我在 this post 中看到它很容易通过以下方式在同一行上打印(覆盖以前的内容):

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

最佳答案

您可以使用 curses module 来实现.

The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.

每个线程都可以编辑其全局字符串变量,您可以在主线程中使用 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()

关于Python:在多线程应用程序中为每个线程打印单独的 bash 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36622122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com