【问题标题】:How can I do an "if run from ipython" test in Python?如何在 Python 中进行“如果从 ipython 运行”测试?
【发布时间】:2011-03-21 11:14:09
【问题描述】:

为了便于从 Ipython 进行调试,我在脚本的开头包含以下内容

from IPython.Debugger import Tracer
debug = Tracer()

但是,如果我从命令行启动我的脚本

$ python myscript.py

我收到与 Ipython 相关的错误。有没有办法做到以下几点

if run_from_ipython():
    from IPython.Debugger import Tracer
    debug = Tracer()

这样我只在需要时才导入 Tracer() 函数。

【问题讨论】:

    标签: python ipython


    【解决方案1】:

    这可能是您正在寻找的东西:

    def run_from_ipython():
        try:
            __IPYTHON__
            return True
        except NameError:
            return False
    

    【讨论】:

    【解决方案2】:

    Python 的方法是使用异常。喜欢:

    try:
        from IPython.Debugger import Tracer
        debug = Tracer()
    except ImportError:
        pass # or set "debug" to something else or whatever
    

    【讨论】:

    • +1 在 Python 中更常见的是尝试事物而不是测试事物
    猜你喜欢
    • 2014-02-24
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2012-01-19
    • 2013-12-20
    • 2022-06-17
    相关资源
    最近更新 更多