Skip to content
Advertisement

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

Advertisement

Answer

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.

Advertisement