带有标题的控制台中的文本进度栏 [英] Text Progress Bar in Console w/ title above

查看:74
本文介绍了带有标题的控制台中的文本进度栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用答案来打印进度条
,但希望它在进行过程中打印其实际操作。
我向print_progress()添加了一个名为 current_task的参数,现在希望其执行如下。我该怎么做?

I am using this answer to print a progress bar but want it to print what exactly it is doing while it is progressing. I added a parameter called "current_task" to print_progress() and now would like it to perform as follows. How do I do this?

仅供参考:我正在使用Unix系统:macOS Sierra

FYI: I'm on on a Unix system: macOS Sierra

print_progress(7,10,...remaining params..., "downloading contacts")

应该打印此


当前正在下载联系人< br>
进展|█████████████████████████████████---------- ----------- | 70%
完成

Currently downloading contacts
Progress |████████████████████████████████---------------------| 70% Complete

后续调用

print_progress(8,10,...remaining params..., "downloading companies")

应该导致进度条更改为现在的样子

should cause the progress bar to change in place to now look like this


当前正在下载公司

进展|██████████████████████████████████████--------- ---- | 80%
完成

Currently downloading companies
Progress |████████████████████████████████████-------------| 80% Complete


推荐答案

这是支持标题行的Greenstick代码。它使用 ANSI控制序列 '\x1b [3A '在打印标题&后将终端光标向上移动3行。

Here's a modified version of Greenstick's code that supports a header line. It uses an ANSI control sequence '\x1b[3A' to move the terminal cursor up 3 lines after it's printed the header & progress bar.

此更新的版本可在Python 2上正确运行(在2.6.6上测试)。 Python 3(在3.6.0上测试)。它还会擦除标题行的先前内容,因此,如果当前标题比上一个短,您就不会得到流浪字符。

This updated version works correctly on Python 2 (tested on 2.6.6) & Python 3 (tested on 3.6.0). It also erases the previous contents of the header line so you don't get stray characters if the current header is shorter than the previous one.

from __future__ import print_function
from time import sleep

# Print iterations progress
#Originally written by Greensticks, modified by PM 2Ring
def printProgressBar (iteration, total, prefix='', suffix='', decimals=1, 
    length=100, fill=u'\u2588', header=''):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
        header      - Optional  : header string (Str)
    """
    # Clear the current line and print the header
    print('\x1b[2K', header, '\n')
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    # Generate and print the bar
    bar = fill * filledLength + u'-' * (length - filledLength)
    print('%s |%s| %s%% %s\x1b[3A' % (prefix, bar, percent, suffix))
    # Print New Lines on Complete
    if iteration == total: 
        print('\n' * 2)

# Test

maxi = 10
delay = 0.5

# Initial call to print 0% progress
header = 'Currently downloading contacts now'
printProgressBar(0, maxi, prefix='Progress:', suffix='Complete', length=50, header=header)
for i in range(1, 8):
    # Do stuff...
    sleep(delay)
    # Update Progress Bar
    printProgressBar(i, maxi, prefix='Progress:', suffix='Complete', length=50, header=header)

header = 'Currently downloading companies'
for i in range(8, maxi + 1):
    # Do stuff...
    sleep(delay)
    # Update Progress Bar
    printProgressBar(i, maxi, prefix='Progress:', suffix='Complete', length=50, header=header)

print('Finished')

请注意不提供标题行,您将获得空白的标题线。请确保标题行实际上适合您终端的一行,并且绝对不要在其中放置任何'\n'字符!

Note that if you don't supply a header line you'll get a blank header line. Please make sure that the header line will actually fit on one line of your terminal, and definitely don't put any '\n' chars in it!

您可以使用线程,如我编写的滚动计时器所示几个月前。

You could make this progress bar more versatile by using threading, as illustrated in this Scrolling Timer I wrote a few months ago.

这是 printProgressBar 的一个版本禁用游标,因此我们不需要在游标开始时增加额外的速度。

Here's a version of printProgressBar that disables the cursor so we don't need that extra pace at the start of the cursor.

def printProgressBar (iteration, total, prefix='', suffix='', decimals=1, 
    length=100, fill=u'\u2588', header=''):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
        header      - Optional  : header string (Str)
    """
    if iteration == 0:
        # Turn off the cursor
        print("\x1b[?25l", end='')
    # Clear the current line & print the header
    print('\x1b[2K', header, sep= '', end='\n\n')
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    # Generate and print the bar
    bar = fill * filledLength + u'-' * (length - filledLength)
    print('%s |%s| %s%% %s\x1b[3A' % (prefix, bar, percent, suffix))
    # Print New Lines on Complete
    if iteration == total: 
        # Turn on the cursor, and skip a few lines
        print("\x1b[?25h", end='\n\n')

这样做的一个问题是如果我们在禁用光标的情况下尽早终止程序(例如,通过按 Ctrl C ),则在程序编辑后仍将被禁用。在Linux上,您只需使用简单的Bash命令发送ANSI序列即可重新打开光标:

One problem with doing this is that if we terminate the program early (eg by hitting CtrlC) while the cursor is disabled, it will still be disabled after the program edits. On Linux, you can just send the ANSI sequence to turn the cursor back on with a simple Bash command:

echo -e "\e[?25h"

尽管更容易重置终端:

echo -e "\ec"

当然,我们也可以捕获 signal.SIGINT 并添加一个处理程序函数以在程序退出之前打开光标,但这会增加程序的复杂性。代码。

Of course, we could also trap signal.SIGINT and add a handler function to turn the cursor on before the program exits, but that adds extra complexity to the code.

这篇关于带有标题的控制台中的文本进度栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆