python - 在 Python 中替换控制台输出

标签 python

我想知道如何像在某些 C/C++ 程序中一样在 Python 中创建那些漂亮的控制台计数器之一。

我有一个循环在做事,当前的输出如下:

Doing thing 0
Doing thing 1
Doing thing 2
...

只有最后一行更新会更整洁;

X things done.

我在许多控制台程序中都看到了这一点,我想知道我是否/如何在 Python 中做到这一点。

最佳答案

一个简单的解决方案是在字符串之前写 "\r" 而不添加换行符;如果字符串永远不会变短,这就足够了......

sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()

稍微复杂一点的是进度条......这是我正在使用的东西:

def start_progress(title):
    global progress_x
    sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
    sys.stdout.flush()
    progress_x = 0

def progress(x):
    global progress_x
    x = int(x * 40 // 100)
    sys.stdout.write("#" * (x - progress_x))
    sys.stdout.flush()
    progress_x = x

def end_progress():
    sys.stdout.write("#" * (40 - progress_x) + "]\n")
    sys.stdout.flush()

你调用 start_progress 传递操作的描述,然后 progress(x) 其中 x 是百分比,最后是 end_progress ()

关于python - 在 Python 中替换控制台输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6169217/

相关文章:

Python:如何在三个列表中找到共同的值

python - 在python中模拟长按键

python - 加速风险 war 游戏掷骰子模拟

python - 从 python 中的数据帧矩阵打印标题值

python - 开发服务器 HTTP 错误 403 : Forbidden

python - Canvas 内的网络抓取图像

python - Django:不可散列类型 :'list' 错误

python - 检查数据框中是否有未命名的列,然后在 Pandas 中返回指示

python - 在 mod_wsgi 上部署 django 应用程序时出现问题

python - 如何使用正则表达式解析只有一个括号的区号电话号码?