我用 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)
我使用Pyinstaller 生成.exe 后,它看起来像这样。
我在这里搜索过类似的问题。似乎人们建议使用 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/