简体   繁体   中英

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

I wrote some animation script with Python and used Pyinstaller to make it an .exe file. The code works fine in PyCharm, ie only displaying single line of progress bar. However, when I open the .exe which I believe is running in shell prompt, it's displaying multiple lines. I'm on Windows 10 and Python 3.7. The issue is easy to replicate on my PC. Below is an example.

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)

If I run it in PyCharm, it looks like this. 在此处输入图片说明

After I use Pyinstaller to generate the .exe, it looks like this. 在此处输入图片说明

I have searched for similar issues here. Seems like people suggest using position=0, but it doesn't work for me. Do I miss anything in my code?

I know I can make the progress bar by myself instead of using tqdm. But I would like to use tqdm if possible as it provides more information like iteration speed and estimated time.

Try passing file=sys.stdout in your call to tqdm . Here is my what I am setting for frames in FuncAnimation :

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

where n_frames is <int> . Remember to import sys .

More detail: I believe the underling reason is that tqdm() has leave=True by default, which means each iteration of the bar will persist wherever it's writing to. Forcing file=sys.stdout tells tqdm to decorate everything for the console. It even adjusts the bar depending on the width of the console. This also works nicely if you're using the telegram feature of tqdm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM