如何在Python中执行“if if impthon”测试?

时间:2021-06-23 20:45:08

To ease debugging from Ipython, I include the following in the beginning of my scripts

为了简化Ipython的调试,我在脚本的开头添加了以下内容

from IPython.Debugger import Tracer
debug = Tracer()

However, if I launch my script from the command line with

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

$ python myscript.py

I get an error related to Ipython. Is there a way to do the following

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

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

This way I only import the Tracer() function when I need it.

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

2 个解决方案

#1


43  

This is probably the kind of thing you are looking for:

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

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

#2


11  

The Python way is to use exceptions. Like:

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

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

#1


43  

This is probably the kind of thing you are looking for:

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

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

#2


11  

The Python way is to use exceptions. Like:

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

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