【问题标题】:Python - How to make tqdm print one line of progress bar in shell?Python - 如何让 tqdm 在 shell 中打印一行进度条?
【发布时间】:2020-04-02 18:10:48
【问题描述】:

我用 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 中运行它,它看起来像这样。

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

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

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

【问题讨论】:

    标签: python shell progress-bar pyinstaller tqdm


    【解决方案1】:

    尝试在对tqdm 的调用中传递file=sys.stdout。这是我在FuncAnimation 中为帧设置的内容:

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

    其中n_frames<int>。记得import sys

    更多细节: 我相信根本原因是tqdm() 默认具有leave=True,这意味着该栏的每次迭代都会在其写入的任何地方持续存在。强制 file=sys.stdout 告诉 tqdm 为控制台装饰所有内容。它甚至可以根据控制台的宽度调整栏。如果您使用 tqdm 的电报功能,这也很有效。

    【讨论】:

      猜你喜欢
      • 2019-08-15
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 2017-07-01
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多