简体   繁体   中英

How do I log tqdm console output to a file in Python?

I'm working on a task that requires me to log the console output of tqdm to a file.

Using the below snippet tqdm shows progress bars in the console.

import time
from tqdm import tqdm

for x in tqdm(range(10)):
    time.sleep(.5)

I used the file parameter to log the output to a file like this:

import time
from tqdm import tqdm

for x in tqdm(range(10), file = open('/tmp/temp_log.log', 'w')):
    time.sleep(.5)

and I'm able to achieve my expected output. However when I use the file param, tqdm does not print any progress bars to the console.

How do can I print the progress bars to the console while logging the output to a file simultaneously?

I've tried using the tqdm-logger module but it only logs the final progress bar as opposed to logging all the bars

After hours of brain storming I found a smart way to tackle this issue:

To display the tqdm console output, wrap the existing tqdm object (the logger) with another tqdm object like this:

import time
from tqdm import tqdm

for x in tqdm(

tqdm(range(10), file = open('/tmp/temp_log.log', 'w')),

 desc = 'TQDM Console'):

    time.sleep(.5)

The snippet now logs and outputs identical bars and timings.

Try to update the bar manually.

pbar = tqdm(total = 10)
for x in tqdm(range(10), file = open('/tmp/temp_log.log', 'w')):
    pbar.update(1)
    time.sleep(.5)

That code creates a log file and shows the bar. It's like using a second bar.

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