我在另一个(父)笔记本中使用 %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 anif __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/