Dim*_*old 3 python ipython spyder jupyter-notebook tqdm
我正在使用tqdm在 python 中显示进度条的包。
tqdm 还有一个用于 Jupyter 笔记本 ( tqdm_notebook())的小部件,允许一个漂亮的“网络式”进度条。
我的问题是我在code.py文件中有一个 tqdm 进度条,我将它导入到 jupyter notebook 中。
在code.py从常规 python 环境(即Ipython, IDLE, shell)运行时,我希望 tqdm 以正常形式运行:
from tqdm import tqdm
a = 0
for i in tqdm(range(2000)):
a+=i
Run Code Online (Sandbox Code Playgroud)
但是当我导入code.pyJupyter 时,我希望它使用tqdm_notebook():
from tqdm import tqdm_notebook as tqdm
a = 0
for i in tqdm(range(2000)):
a+=i
Run Code Online (Sandbox Code Playgroud)
如何让python区分环境?
我发现这篇文章建议检查get_ipython().__class__.__name__或'ipykernel' in sys.modules
但它没有区分笔记本和其他 Ipython shell(例如在 Spyder 或 IDLE 中)。
tqdm现在有一个autonotebook模块。从文档:
可以使用 autonotebook 子模块让 tqdm 在控制台或笔记本版本之间自动选择:
from tqdm.autonotebook import tqdm
tqdm.pandas()
Run Code Online (Sandbox Code Playgroud)
请注意,这将发出TqdmExperimentalWarningif run in a notebook,因为这意味着无法区分 jupyter notebook 和 jupyter console。使用 auto 而不是 autonotebook 来抑制此警告。