python - 在屏幕上显示进度条以及其他输出

标签 python progress-bar command-line-interface

我正在编写一个处理文件的 Python 命令行脚本。

我想要一个进度条来显示已完成的工作量,但我也希望在屏幕上看到一些额外的输出。

我找到了this script这对进度条有很大帮助,但我没有找到如何添加额外的输出。

我想要的是这样的输出:

[======              ] 30%
Error: File 'test.png' could not be processed.
Error: File 'yet_another_test.jpg' could not be processed.

进度条随着处理的发生而更新...

提前致谢!

最佳答案

不知道这是不是你想要的。希望对您有所帮助。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys
import time
import math

# Output example: [=======   ] 75%

# width defines bar width
# percent defines current percentage
def progress(width, percent):
    marks = math.floor(width * (percent / 100.0))
    spaces = math.floor(width - marks)

    loader = '[' + ('=' * int(marks)) + (' ' * int(spaces)) + ']'

    sys.stdout.write("%s %d%%\r" % (loader, percent))
    if percent >= 100:
        sys.stdout.write("\n")
    sys.stdout.flush()

def func():    
    try:
        # you can do your things here
        assert 0, 'hahahah'
    except Exception as e:
        sys.stdout.write(repr(e)+'\r')
        sys.stdout.flush()    


# Simulate doing something...
for i in xrange(100):
    progress(50, (i + 1)) # +1 because xrange is only 99
    if i == 6:
        func()
    time.sleep(0.1) # Slow it down for demo

关于python - 在屏幕上显示进度条以及其他输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25395752/

相关文章:

php - 如何使用 php 将 bash 颜色代码解析为 html

java - Android 卡住进度对话框

c++ - 缩放进度条值

linux - 从 CLI 检查 Berkeley DB 文件

python - 为什么我在 Tkinter 中出现未绑定(bind)的本地错误

c# - 为什么 ProgressBar.SetValue 会抛出具有有效值的 ArgumentException?

c - 将 cmp 与进程替换 (stdout) 一起使用? ( bash )

python - 为什么 Python 解释器不返回明确的 SyntaxError 消息?

python - Python 3.4 功能需要哪个版本的 ‘unittest2’?

python - Pandas 面板 : Copy versus view