I'm using tqdm to display progress bars while some long-running Django management commands complete. It works great (so easy to use!), but...
When I run unit tests over my code, I want to stop the progress bars from outputting. And if I run those commands in the background using cron or some other means, I'd also want the progress bars not to be in the output.
I can't see an easy way to do these two things, but perhaps I've missed something?
There is a disable
argument which you can set to True
to silence any tqdm
output (and in fact it will totally skip the progress bar calculations too, not just the display).
To dynamically switch it, you can just add a commandline argument to your script that will define if disable
is set or not. This should work for both unit testing and cron.
Example using the 'disable' parameter:
from tqdm import tqdm
import time
for i in tqdm(range(10), disable=True):
time.sleep(1)
This is very common use case when you need to globally disable all tqdm
's, desirably without changing the code in all places where it is used and which you probably do not control. Discussions about implementing such a feature last many years and lead to nothing (1, 2, 3, 4). Users need to patch tqdm in order to stop polluting logs. One of the shortest ways I found is probably this:
from tqdm import tqdm
from functools import partialmethod
tqdm.__init__ = partialmethod(tqdm.__init__, disable=True)
The idea is defaulting the already supported (but not sufficient) parameter of the initializer. It is not sufficient because you need to add it in each place where tqdm is instantiated, which you don't want, that's why we modify __init__
to make such a default.
The patch works independently of the order of imports and will affect all subsequently created tqdm
objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With