I'd like to use tqdm in my script but not require others to use it if they haven't installed it.
I've found this:
try:
import tqdm
except ImportError:
tqdm = None
But I'm not sure how to use tqdm==None
with this:
with tqdm.tqdm(total=totalSize) as pbar:
Where totalSize
is the file size (or sum of file sizes when looping over multiple files).
The way I usually do it is by adding the following shim:
try:
from tqdm import tqdm
except ImportError:
def tqdm(iterator, *args, **kwargs):
return iterator
Now, you can just always use tqdm without having to worry about whether or not it exists, as the fallback will pass through the thing you're iterating over, ignoring all tqdm related options.
for item in tqdm(items):
action(item)
Admittedly your usage (using with
) isn't compatible with this approach - but I'll leave this here for people using it in a for loop like I usually use it.
With help from tqdm's documentation and my try/except logic, I have this working:
try:
import tqdm
except ImportError:
tqdm = None
if (tqdm == None):
pbar = None
else:
pbar = tqdm.tqdm(total=totalSize)
#... inside the loop processing my file[s]...
if (pbar):
pbar.update(len(line))
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.