2011-03-21 42 views
23

從IPython的緩解調試,我包括我的劇本的開頭以下如何在Python中執行「如果從ipython運行」測試?

from IPython.Debugger import Tracer 
debug = Tracer() 

但是,如果我在命令行啓動我的腳本

$ python myscript.py 

我得到相關的錯誤IPython的。有沒有辦法做到以下幾點:

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

這樣我只在需要時才導入Tracer()函數。

回答

38

這可能是東西你正在尋找的那種:

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

更詳細的IPython配置檢測(是否pylab加載和內聯模式)在這裏討論:http://stackoverflow.com/questions/15341757/how-to-check-that-pylab-backend-of-matplotlib-runs-inline/17826459#17826459 – 2013-07-24 06:14:37

10

Python的方式是使用異常。像:

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

+1多見於Python中嘗試的事情,而不是測試的東西 – 2011-03-21 17:06:04

相關問題