【问题标题】:Is it possible to know if you are in ipython or not?是否有可能知道您是否在 ipython 中?
【发布时间】:2012-02-01 09:33:05
【问题描述】:

即你能做类似的事情吗:

if we_are_in_ipython:
    do_some_ipython_specific_stuff()

normal_python_stuff()

我想我正在尝试做的是非常松散地沿着 C# 中的#if DEBUG 行(即使用 ipython 作为调试工具和命令行 python 来运行代码而没有调试的东西)。

【问题讨论】:

  • IPython 不是主要用于交互式使用吗?那么您可能知道您正在使用它。
  • 看起来像 stackoverflow.com/q/5376837/407651 的副本
  • 好吧,也许一个具体的例子会有所帮助。如果我使用的是 ipython,我将 from IPython.Debugger import Tracer; debug_here = Tracer() 行放在文件顶部,然后将 debug_here() 语句放在整个文件中。但是,第一行会从命令行 (AttributeError: 'function' object has no attribute 'colors') 生成错误,另外我不希望 debug_here() 语句被调用
  • @user647772 如果你想在 IPython/Jupyter 中编写一个支持附加功能的库,你需要一种方法来解决这个问题。

标签: python debugging ipython


【解决方案1】:

检查__IPYTHON__ 变量:

def is_ipython():
    try:
        __IPYTHON__ 
        return True
    except: 
        return False

【讨论】:

  • 如果我有__IPYTHON__ 作为变量怎么办
  • Python 使用 __name__ 和前导和尾随下划线来表示具有预定义行为的特殊系统函数。这将是程序员的一个糟糕的命名法,这就是我的感受。
【解决方案2】:

duplicate 中所述,您可以使用 try/except 方法,或者

if '__IP' in globals():
    # stuff for ipython
    pass

或者检查内置的__IPYTHON__

import __builtin__
if hasattr(__builtin__, '__IPYTHON__'):
    # stuff for ipython
    pass

【讨论】:

    【解决方案3】:

    是的。

    if 'get_ipython' in dir():
        """
           when ipython is fired lot of variables like _oh, etc are used.
           There are so many ways to find current python interpreter is ipython.
           get_ipython is easiest is most appealing for readers to understand.
        """
        do_some_thing_
    else:
        don_sonething_else
    

    【讨论】:

    • 我很高兴知道为什么有人 -1 我的回答。
    猜你喜欢
    • 2016-08-19
    • 2019-09-25
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    相关资源
    最近更新 更多