测试 IPython 是否存在

gt6*_*89b 3 python ipython

我有相同的代码,我偶尔从命令行运行它,python source.py偶尔将其复制/粘贴到交互式 IPython 中。我想以两种方式执行稍微不同的代码,并尝试将差异嵌入到以下代码块中:

try:
    __IPYTHON__
    # do IPython-mode code
except NameError:
    # do script-mode code
Run Code Online (Sandbox Code Playgroud)

我知道在 Python 中这是一种常见的技术,但它搞砸了 PyCharm 中的自动标记,我希望找到一些更有吸引力的方法来测试 IPython 的存在,也许通过测试'__IPYTHON__' in ...或类似的方法。然而,我看到这个符号既不在locals()也不在 中globals()。有没有其他地方可以测试它的存在,或者任何其他更常规的测试,而不直接使用异常?

我正在使用 Python 2.7.11 和 IPython 5.1.0。非常感谢。

更新相关但无帮助:How do I check if a variable isn’t?

hvw*_*dow 5

我想你正在寻找

if hasattr(__builtins__, '__IPYTHON__'):
    print('IPython')
else:
    print('Nope')
Run Code Online (Sandbox Code Playgroud)