Python - 如何让 tqdm 在 shell 中打印一行进度条?

标签 python shell progress-bar pyinstaller tqdm

我用 Python 编写了一些动画脚本,并使用 Pyinstaller 将其制作为 .exe 文件。该代码在 PyCharm 中运行良好,即仅显示单行进度条。但是,当我打开我认为在 shell 提示符下运行的 .exe 时,它​​显示多行。我在 Windows 10 和 Python 3.7 上。这个问题很容易在我的电脑上重现。下面是一个例子。

import matplotlib.pyplot as plt
import matplotlib.animation as ani
import numpy as np
import pandas as pd
from tqdm import tqdm


fig = plt.figure(figsize=(20,12))
ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2, rowspan=2)
def test(i):
    data = np.random.normal(0, 1, i+1)
    pd.DataFrame(data).plot(kind='bar', ax=ax1)


Writer = ani.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1000)

anim = ani.FuncAnimation(fig=fig, func=test, frames=tqdm(range(10), initial=1, position=0), interval=200, blit=False)
anim.save('textmovie.mp4', writer=writer)

如果我在 PyCharm 中运行它,它看起来像这样。 enter image description here

我使用Pyinstaller 生成.exe 后,它看起来像这样。 enter image description here

我在这里搜索过类似的问题。似乎人们建议使用 position=0,但它对我不起作用。我的代码中是否遗漏了任何内容?

我知道我可以自己制作进度条而不是使用 tqdm。但我想尽可能使用 tqdm,因为它提供了更多信息,例如迭代速度和估计时间。

最佳答案

尝试传递 file=sys.stdout在您调用 tqdm 的电话中.这是我在 FuncAnimation 中为框架设置的内容:

frames=tqdm(range(n_frames), file=sys.stdout) ,

哪里n_frames<int> .记得import sys .

更多细节: 我相信潜在的原因是tqdm()leave=True默认情况下,这意味着条形图的每次迭代都会在写入的任何地方持续存在。强制file=sys.stdout告诉 tqdm 为控制台装饰一切。它甚至可以根据控制台的宽度调整栏。如果您使用 tqdm 的电报功能,这也能很好地工作。

关于Python - 如何让 tqdm 在 shell 中打印一行进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60998231/

相关文章:

python - 如何沿数组维度映射克罗内克乘积?

用于过滤 git status 命令的 Linux Shell 脚本

perl - 如何向 WWW::Mechanize 添加进度条?

python - 当使用大数组作为输入数据时出现 CUDA 错误

python - 为什么在Python中创建namedtuple对象后无法读取 'typename'

php - PHP shell 脚本 : "Could not open input file" 的问题

linux - 无法在 Shell 脚本的旧版中执行 echo

wpf - 进度条条样式右半径

Python 显示进度

python - 在 Linux 上忽略 glob() 中的大小写