python - 在 Python 中同时在控制台中打印 2 行

标签 python multithreading

我正在使用 Python 3 在控制台中输出 2 个进度条,如下所示:

100%|###############################################|       
 45%|######################                         |

两个条在不同的线程中同时增长。

线程操作很好,两个进度条都在完成它们的工作,但是当我想打印它们时,它们在控制台的一行上彼此重叠打印。我只有一行进度条,它交替显示这两个进度条。

有什么方法可以让这些进度条同时在不同的行上增长?

最佳答案

您需要一个 CLI 框架。如果您在 Unix 上工作,Curses 是完美的选择(并且可以在此处找到适用于 Windows 的端口:https://stackoverflow.com/a/19851287/1741450)

enter image description here

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()

关于python - 在 Python 中同时在控制台中打印 2 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21239032/

相关文章:

Python:获取两个点数字之间的范围

python - 在 I/O 重定向中执行 Python 脚本时出现 EOFError

python - VisibleDeprecationWarning - 这是从哪里来的?

python - 如何拆分字符串并指定为 pandas 数据框的列名称?

Python Pandas 从列中删除非数字行

multithreading - CopyFileEx 可以从辅助线程调用吗?

android - Android-将不确定的ProgressBar与另一个线程一起使用

ios - 如何等待 NSURLConnection 委托(delegate)完成后再继续?

java - 使用线程和异步任务无法防止 ANR 错误

C++ 线程库,在完成前两个后启动线程