我正在寻找一种可靠的方法来确定我的模块是从Jupyter笔记本中加载/运行,还是更具体地说,如果ipywidgets可用.
这不是其他问题的重复:我发现的其他一切都没有可靠的解决方案,或者(更常见的情况)他们使用Python中常见的“只是尝试它并且轻轻地失败”的方法.就我而言,我正在尝试编写以下逻辑:
if in_jupyter():
from tqdm import tqdm_notebook as tqdm
else:
from tqdm import tqdm
我不认为“尝试和失败”是一个合适的解决方案,因为我不想产生任何输出.
到目前为止,我找到的最接近解决方案的是:
from IPython import get_ipython
get_ipython().config['IPKernelApp']['parent_appname'] == 'ipython-notebook'
但是这个配置属性是一些看似空的traitlets.config.loader.LazyConfigValue(.get_value(None)只是一个空字符串).
最佳答案 您可以使用以下代码段来确定您是在jupyter,ipython还是在终端中:
def type_of_script():
try:
ipy_str = str(type(get_ipython()))
if 'zmqshell' in ipy_str:
return 'jupyter'
if 'terminal' in ipy_str:
return 'ipython'
except:
return 'terminal'
您可以在How can I check if code is executed in the IPython notebook?找到更多深入的信息