python - IPython %run magic -n 开关不工作

标签 python ipython jupyter-notebook ipython-magic

我在另一个(父)笔记本中使用 %run 魔法运行一个 IPython 笔记本。

如果使用 %run 调用它,我想隐藏子笔记本中的一些输出,我认为我可以通过测试 if __name__ == '__main__'

IPython 文档说,当使用 %run -n 开关时:

__name__ is NOT set to __main__, but to the running file's name without extension (as python does under import). This allows running scripts and reloading the definitions in them without calling code protected by an if __name__ == "__main__" clause.

但是,它对我来说似乎不起作用。我试过这个:

sub_notebook.ipynb 中:

print(__name__)

parent_notebook.ipynb 中:

%run -n sub_notebook.ipynb

这会打印 __main__ 但文档说它应该打印 sub_notebook

请告诉我如何根据它是单独运行还是使用 %run 有选择地运行 sub_notebook.ipynb 中的代码?

我正在运行 IPython 版本 6.1.0

最佳答案

source code to %run设置 __file__ 变量,以便我们可以对此进行测试。

我们可以在sub_notebook.ipynb中写:

try:
    __file__
    print('I am in an imported notebook')

except NameError:
    print('I am not in an imported notebook')

单独运行,打印I am not in an imported notebook

我们可以创建一个父笔记本 parent_notebook.ipynb 包含:

%run sub_notebook.ipynb

正确运行它会打印I am in an imported notebook

我们可以在 sub_notebook.ipynb 中编写一个简单的测试:

def has_parent():
    """Return True if this notebook is being run by calling
    %run in another notebook, False otherwise."""
    try:
        __file__
        # __file__ has been defined, so this notebook is 
        # being run in a parent notebook
        return True

    except NameError:
        # __file__ has not been defined, so this notebook is 
        # not being run in a parent notebook
        return False

然后可以保护父笔记本中不应该打印的代码:

if not has_parent():
    print('This will not print in the parent notebook')

关于python - IPython %run magic -n 开关不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48067529/

相关文章:

python - 复制 .txt 文件并将每个单词的首字母大写并写入新文件

python - 具有导入函数的 sklearn FunctionTransformer

ipython - 无法在 ipython qtconsole 中更改字体大小

ipython - Jupyterhub终端路径变量

Matplotlib 子图大小不相等

python - 如何使用 Pandas 将多个 csv 文件中的单个数据列合并为一个?

python - Pandas groupby 计数在同一行中具有标题

opencv - 如何克服 ipython 中 opencv 的导入错误

python - Matplotlib:如何防止 Jupyter 将大图压缩到单个单元格中?

hadoop - Pyspark Mac NativeCodeLoader : Unable to load native-hadoop library for your platform. .. 在适用的情况下使用内置 java 类