简体   繁体   English

如果在IPython中__name__ =='__ main__'

[英]if __name__ == '__main__' in IPython

I have Python scripts that use the if __name__ == '__main__' trick to have some code only run when the script is called as a script and not when it is loaded into the interactive interpreter. 我有Python脚本使用if __name__ == '__main__'技巧,只有当脚本作为脚本调用时才会运行某些代码,而不是在将脚本加载到交互式解释器时运行。 However, when I edit these scripts from IPython using the %edit command, IPython apparently sets __name__ to '__main__' and so the code gets run every time I exit the editing session. 但是,当我使用%edit命令从IPython编辑这些脚本时,IPython显然将__name__设置为'__main__' ,因此每次退出编辑会话时代码都会运行。 Is there a good way to make this code not run when the module is edited from IPython? 从IPython编辑模块时,是否有一种很好的方法可以使代码不运行?

When working from within Emacs (which I assume is close to what you get with %edit ), I usually use this trick: 当在Emacs中工作时(我假设它接近你使用%edit ),我通常使用这个技巧:

if __name__ == '__main__' and '__file__' in globals():
    # do what you need

For obvious reasons, __file__ is defined only for import 'ed modules, and not for interactive shell. 出于显而易见的原因, __file__仅为import的ed模块定义,而不是为交互式shell定义。

It sounds like you might just need the -x switch: 听起来你可能只需要-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...

When you call %edit -x the code is not executed after you exit your editor. 当您调用%edit -x ,退出编辑器后不会执行代码。

IPython adds the function get_ipython() to the globally available variables. IPython将函数get_ipython()到全局可用变量中。 So you can test, whether this function exist in globals() to make your decision: 所以你可以测试一下globals()是否存在这个函数来做出决定:

if __name__ == '__main__' and "get_ipython" not in dir():
    print "I'm not loaded with IPython"

The above code just tests whether there is a global variable with name get_ipython . 上面的代码只测试是否存在名为get_ipython的全局变量。 To also test whether this variable is callable, you can do: 要测试此变量是否可调用,您可以执行以下操作:

if __name__ == '__main__' and not callable(globals().get("get_ipython", None)):
    print "I'm not loaded with IPython"

IPython automatically executes the code you write with the %edit command. IPython会自动执行您使用%edit命令编写的代码。 You can use %edit -x to specify that you do NOT want to run the code you were just editing. 您可以使用%edit -x指定您不想运行刚刚编辑的代码。

http://ipython.org/ipython-doc/stable/api/generated/IPython.core.magics.code.html http://ipython.org/ipython-doc/stable/api/generated/IPython.core.magics.code.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM