Python tqdm导入检查,如果正在运行jupyter notebook或lab

13

我有一个模块(tqdm),根据我是否在jupyter笔记本或jupyter lab环境中运行我的.ipynb,需要以不同方式导入它。有没有办法在Python中确定这一点?例如:

if <jupyter notebook>:
    from tqdm import tqdm_notebook as tqdm 
elif <jupyter lab>:
    from tqdm import tqdm
else:
    print("Not in jupyter environment.")

1
请参见 https://dev59.com/AWUp5IYBdhLWcg3wPFz_#24937408 和 https://github.com/tqdm/tqdm/issues/443。 - krassowski
1个回答

4
# either:
from tqdm.autonotebook import tqdm
# or to suppress the warning:
from tqdm.auto import tqdm

对于其他模块/检查,请参见如何检查代码是否在IPython笔记本中执行?(但请注意,那里的被接受但不受欢迎的答案是“这是故意设计成不可能的。”)


这只是说明如何导入tqdm,而不是如何检测jupyter! - Tomasz Gandor
这篇文章特别讨论了tqdm。如果你想要一个更通用的测试,可以在评论中找到另一个答案。 - casper.dcl
OP提供了tqdm作为一个例子。这篇文章是否应该重新命名为“如何在Jupyter中导入tqdm”?因为现在它出现在错误的搜索结果中,而不是:https://dev59.com/AWUp5IYBdhLWcg3wPFz_。 - Tomasz Gandor
嗯,看起来是这样。 - casper.dcl
1
更新的标题和答案 - casper.dcl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接