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

3
我用Python编写了一些动画脚本,并使用Pyinstaller将其制作成.exe文件。在PyCharm中,代码可以正常运行,即只显示单行进度条。然而,当我打开.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中运行它,它看起来像这样。 输入图像描述 在我使用Pyinstaller生成.exe之后,它看起来像这样。 输入图像描述 我在这里搜索了类似的问题。似乎人们建议使用position=0,但对我不起作用。我的代码有什么问题吗?
我知道我可以自己制作进度条,而不是使用tqdm。但如果可能的话,我想使用tqdm,因为它提供更多信息,如迭代速度和预计时间。
1个回答

1
尝试在调用 tqdm 时传递 file=sys.stdout。以下是我在 FuncAnimation 中为帧设置的内容: frames=tqdm(range(n_frames), file=sys.stdout)
其中,n_frames<int>。记得要导入 sys
更多细节: 我认为根本原因是 tqdm() 默认具有 leave=True,这意味着进度条的每次迭代都会持久存在于其写入的位置。强制使用 file=sys.stdout

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接