【问题标题】:How to output above the last printed line?如何在最后一个打印行之上输出?
【发布时间】:2017-09-08 11:31:54
【问题描述】:

python 中有没有办法在命令行中打印最后一行上方的内容?或者,与我想要实现的类似,保持最后一行不变,即不覆盖它。

这样做的目的是让命令行中的最后一行成为状态/百分比条。

输出示例:

File 1 processed
(0.1% Completed)

下次刷新:

File 1 processed
File 2 processed
(0.2% Completed)

下次刷新:

File 1 processed
File 2 processed
File 3 processed
(0.3% Completed)

【问题讨论】:

    标签: python command-line printing format output


    【解决方案1】:
    from time import sleep
    erase = '\x1b[1A\x1b[2K'
    
    def download(number):
        print(erase + "File {} processed".format(number))
    
    def completed(percent):
        print("({:1.1}% Completed)".format(percent))
    
    for i in range(1,4):
        download(i)
        completed(i/10)
        sleep(1)
    

    在我的 python 3.4 中工作,最终输出是:

    File 1 processed
    File 2 processed
    File 3 processed
    (0.3% Completed)
    

    如果您想了解有关终端转义码的更多信息,请参阅: 维基百科的ANSI escape codes 文章。

    根据要求,带空格的示例:

    from time import sleep
    erase = '\x1b[1A\x1b[2K'
    
    def download(number):
        print(erase*2 + "File {} processed".format(number))
    
    def completed(percent):
        print("\n({:1.1}% Completed)".format(percent))
    
    print("\n(0.0% Completed)")
    for i in range(1,5):
        download(i)
        completed(i/10)
        sleep(1)
    

    最终输出为:

    File 1 processed
    File 2 processed
    File 3 processed
    File 4 processed
    
    (0.4% Completed)
    

    【讨论】:

    • 如果我想在处理的文件块和百分比之间留一个空行怎么办?我认为这会很棘手
    • 如果我理解正确,完全没有,我已经在答案中添加了示例。
    【解决方案2】:

    看看\r 命令。这可以解决问题。

    for i in range(2):
        print '\rFile %s processed' % i
        print '(0.%s%% Completed)' % i,
    

    输出是:

    File 0 processed
    File 1 processed
    (0.1% Completed)
    

    【讨论】:

    • 这可行,但仅适用于这种特定情况。图片 我有来自不同进程(多处理模块)的多个输出,我想跟踪进度百分比。
    • @PyCV 如果你有多个进程并且你想协调显示,他们应该把他们的输出都发送到一个地方来做。如果您正在做一个多处理池,imap_unordered 将是一个好方法。
    猜你喜欢
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 2021-07-03
    相关资源
    最近更新 更多