【问题标题】:Check if module is running in Jupyter or not检查模块是否在 Jupyter 中运行
【发布时间】:2017-11-09 20:52:26
【问题描述】:

我正在寻找一种可靠的方法来确定我的模块是否正在从 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)只是一个空字符串)。

【问题讨论】:

    标签: python jupyter-notebook jupyter


    【解决方案1】:

    您可以使用以下 sn-p 来确定您是在 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?找到更深入的信息

    【讨论】:

      【解决方案2】:

      如果你有tqdm >= 4.27.0,你可以从tqdm.auto 导入来处理这个:

      from tqdm.auto import tqdm
      

      tqdm 然后可以正常使用。如果你在笔记本中,tqdm 将从.notebook 导入。

      【讨论】:

        【解决方案3】:

        您可以检查type(get_ipython()) 是否来自ipykernel,例如如果

        type(get_ipython()).__module__.startswith('ipykernel.')
        

        但我不确定它有多稳定。

        【讨论】:

        • 这确实有效,但我也担心稳定性。
        猜你喜欢
        • 2021-09-10
        • 1970-01-01
        • 2018-11-27
        • 2019-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-03
        相关资源
        最近更新 更多