[英]if __name__ == '__main__' in IPython
我有Python脚本使用if __name__ == '__main__'
技巧,只有当脚本作为脚本调用时才会运行某些代码,而不是在将脚本加载到交互式解释器时运行。 但是,当我使用%edit
命令从IPython编辑这些脚本时,IPython显然将__name__
设置为'__main__'
,因此每次退出编辑会话时代码都会运行。 从IPython编辑模块时,是否有一种很好的方法可以使代码不运行?
当在Emacs中工作时(我假设它接近你使用%edit
),我通常使用这个技巧:
if __name__ == '__main__' and '__file__' in globals():
# do what you need
出于显而易见的原因, __file__
仅为import
的ed模块定义,而不是为交互式shell定义。
听起来你可能只需要-x
开关:
In [1]: %edit
IPython will make a temporary file named: /tmp/ipython_edit_J8j9Wl.py
Editing... done. Executing edited code...
Name is main -- executing
Out[1]: "if __name__ == '__main__':\n print 'Name is main -- executing'\n"
In [2]: %edit -x /tmp/ipython_edit_J8j9Wl
Editing...
当您调用%edit -x
,退出编辑器后不会执行代码。
IPython将函数get_ipython()
到全局可用变量中。 所以你可以测试一下globals()
是否存在这个函数来做出决定:
if __name__ == '__main__' and "get_ipython" not in dir():
print "I'm not loaded with IPython"
上面的代码只测试是否存在名为get_ipython
的全局变量。 要测试此变量是否可调用,您可以执行以下操作:
if __name__ == '__main__' and not callable(globals().get("get_ipython", None)):
print "I'm not loaded with IPython"
IPython会自动执行您使用%edit
命令编写的代码。 您可以使用%edit -x
指定您不想运行刚刚编辑的代码。
http://ipython.org/ipython-doc/stable/api/generated/IPython.core.magics.code.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.