[英]Print 2 lines in the console concurrently in Python
I'm using Python 3 to output 2 progress bars in the console like this: 我正在使用Python 3在控制台中输出2个进度条,如下所示:
100%|###############################################|
45%|###################### |
Both bars grow concurrently in separate threads. 两个条都在不同的线程中同时增长。
The thread operations are fine and both progress bars are doing their job, but when I want to print them out they print on top of each other on one line in the console. 线程操作很好,两个进度条都在执行它们的工作,但是当我想要打印它们时,它们在控制台中的一行上相互打印。 I just got one line progress bar which alternates between showing these 2 progress bars. 我只有一个行进度条,它在显示这两个进度条之间交替显示。
Is there any way these progress bars can grow on separate lines concurrently? 这些进度条是否可以同时在不同的行上增长?
You need a CLI framework. 您需要一个CLI框架。 Curses
is perfect if you are working on Unix (and there is a port for Windows which can be found here : https://stackoverflow.com/a/19851287/1741450 ) 如果您在Unix上工作, Curses
是完美的(并且有一个Windows端口可以在这里找到: https : //stackoverflow.com/a/19851287/1741450 )
import curses
import time
import threading
def show_progress(win,X_line,sleeping_time):
# This is to move the progress bar per iteration.
pos = 10
# Random number I chose for demonstration.
for i in range(15):
# Add '.' for each iteration.
win.addstr(X_line,pos,".")
# Refresh or we'll never see it.
win.refresh()
# Here is where you can customize for data/percentage.
time.sleep(sleeping_time)
# Need to move up or we'll just redraw the same cell!
pos += 1
# Current text: Progress ............... Done!
win.addstr(X_line,26,"Done!")
# Gotta show our changes.
win.refresh()
# Without this the bar fades too quickly for this example.
time.sleep(0.5)
def show_progress_A(win):
show_progress( win, 1, 0.1)
def show_progress_B(win):
show_progress( win, 4 , 0.5)
if __name__ == '__main__':
curses.initscr()
win = curses.newwin(6,32,14,10)
win.border(0)
win.addstr(1,1,"Progress ")
win.addstr(4,1,"Progress ")
win.refresh()
threading.Thread( target = show_progress_B, args = (win,) ).start()
time.sleep(2.0)
threading.Thread( target = show_progress_A, args = (win,)).start()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.