简体   繁体   English

如何不要求安装tqdm?

[英]How can I not require tqdm to be installed?

I'd like to use tqdm in my script but not require others to use it if they haven't installed it. 我想在脚本中使用tqdm,但如果其他人尚未安装,则不要求其他人使用它。

I've found this: 我发现了这一点:

try:
    import tqdm
except ImportError:
    tqdm = None

But I'm not sure how to use tqdm==None with this: 但是我不确定如何使用tqdm==None

with tqdm.tqdm(total=totalSize) as pbar:

Where totalSize is the file size (or sum of file sizes when looping over multiple files). 其中totalSize是文件大小(或遍历多个文件时文件大小的总和)。

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. 现在,您可以始终使用tqdm,而不必担心它是否存在,因为回退将遍历您正在迭代的事物,而忽略所有与tqdm相关的选项。

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 )与这种方法不兼容-但我会将其留给这里的人在for循环中使用,就像我通常使用的那样。

With help from tqdm's documentation and my try/except logic, I have this working: 在tqdm 文档和try / except逻辑的帮助下,我可以进行以下工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM