The Singularity
The Singularity

Reputation: 2698

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

Upvotes: 3

Views: 2067

Answers (2)

The Singularity
The Singularity

Reputation: 2698

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(0.5)

The snippet now logs and outputs identical bars and timings.

Upvotes: 3

Oivalf
Oivalf

Reputation: 154

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.

Upvotes: 0

Related Questions