【问题标题】:if __name__ == '__main__' in IPython如果 __name__ == '__main__' 在 IPython
【发布时间】:2014-04-07 21:00:01
【问题描述】:

我的 Python 脚本使用 if __name__ == '__main__' 技巧使某些代码仅在脚本作为脚本调用时运行,而不是在将其加载到交互式解释器中时运行。但是,当我使用 %edit 命令从 IPython 编辑这些脚本时,IPython 显然将 __name__ 设置为 '__main__',因此每次退出编辑会话时代码都会运行。当从 IPython 编辑模块时,有没有一种好方法可以让这段代码不运行?

【问题讨论】:

    标签: python ipython


    【解决方案1】:

    在 Emacs 中工作时(我认为这与使用 %edit 得到的结果接近),我通常使用这个技巧:

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

    出于显而易见的原因,__file__ 只为import'ed 模块定义,而不是为交互式 shell 定义。

    【讨论】:

    • 对于那些不知道 Jupyter 笔记本是从 IPython 笔记本开发的,我会指出第二部分的添加在 Jupyter 笔记本中有效,因此粘贴时相关的代码块不会运行进入笔记本的单元格。此外,考虑到这一点的人可能会对here 的方法感兴趣。
    【解决方案2】:

    听起来您可能只需要-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 时,退出编辑器后代码不会执行。

    【讨论】:

    • -x 开关至关重要。
    • 谢谢;这很有用,但它并不能完全满足我的要求,因为我希望 IPython 加载模块中定义的函数/类,而不是运行与模块关联的测试代码。
    • 没问题。我想你可能会有这样的澄清。鉴于此,我个人会推荐@ffriend的回答。
    【解决方案3】:

    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"
    

    【讨论】:

      【解决方案4】:

      IPython 会自动执行您使用%edit 命令编写的代码。您可以使用%edit -x 指定您不想运行刚刚编辑的代码。

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

      【讨论】:

        猜你喜欢
        • 2015-09-12
        • 2018-03-13
        • 2020-06-05
        • 2017-07-03
        • 1970-01-01
        • 2013-12-11
        • 2018-11-01
        • 2016-12-22
        • 2010-12-30
        相关资源
        最近更新 更多