簡體   English   中英

Python - 如何讓 tqdm 在 shell 中打印一行進度條?

[英]Python - How to make tqdm print one line of progress bar in shell?

我用 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,因為它提供了更多信息,如迭代速度和估計時間。

嘗試在您對tqdm的調用中傳遞file=sys.stdout 這是我在FuncAnimation為幀設置的FuncAnimation

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

其中n_frames<int> 記得import sys

更多細節:我相信tqdm()原因是tqdm()默認情況下有leave=True ,這意味着 bar 的每次迭代都會在寫入的地方持續存在。 強制file=sys.stdout告訴 tqdm 裝飾控制台的所有內容。 它甚至會根據控制台的寬度調整欄。 如果您使用 tqdm 的電報功能,這也很有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM