如果在IPython中__name__ =='__ main__' [英] if __name__ == '__main__' in IPython

查看:114
本文介绍了如果在IPython中__name__ =='__ main__'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Python脚本使用如果__name__ =='__ main __'技巧,只有当脚本作为脚本调用时才会运行某些代码而不是加载到交互式解释器中。但是,当我使用%edit 命令从IPython编辑这些脚本时,IPython显然将 __ name __ 设置为'__ main __'因此每次退出编辑会话时代码都会运行。从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. 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. Is there a good way to make this code not run when the module is edited from IPython?

推荐答案

在Emacs中工作时(我假设它接近你用%edit 获得的东西,我通常使用这个技巧:

When working from within Emacs (which I assume is close to what you get with %edit), I usually use this trick:

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

出于显而易见的原因, __ file __ 仅针对 import 'ed模块定义,而不是交互式shell。

For obvious reasons, __file__ is defined only for import'ed modules, and not for interactive shell.

这篇关于如果在IPython中__name__ =='__ main__'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆