在IPython中使用if __name__ == '__main__
我有一些Python脚本,它们使用了一个叫做if __name__ == '__main__'
的技巧,这样一些代码只有在脚本被直接运行时才会执行,而在交互式解释器中加载时不会执行。不过,当我在IPython中用%edit
命令编辑这些脚本时,IPython似乎把__name__
设置成了'__main__'
,这样每次我退出编辑会话时,这些代码就会被执行。有没有什么好的办法让这些代码在从IPython编辑模块时不执行呢?
4 个回答
2
在IPython中,当你使用%edit
这个命令时,它会自动执行你写的代码。如果你不想运行刚才编辑的代码,可以使用%edit -x
这个命令来指定。
http://ipython.org/ipython-doc/stable/api/generated/IPython.core.magics.code.html
8
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"
11
听起来你可能只需要使用 -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
时,代码在你退出编辑器后不会被执行。
27
在使用Emacs的时候(我想这和你用%edit
时的情况差不多),我通常会用这个小技巧:
if __name__ == '__main__' and '__file__' in globals():
# do what you need
显而易见,__file__
这个东西只在被import
的模块中定义,而在交互式命令行中是没有的。