2016-03-31 9 views
0

與IPython的Qt的外殼採用的代碼是這樣的我的應用程序接口:如何獲取sys.exc_traceback表單IPython shell.run_code?

from IPython.core.interactiveshell import ExecutionResult 
shell = self.kernelApp.shell # ZMQInteractiveShell 
code = compile(script, file_name, 'exec') 
result = ExecutionResult() 
shell.run_code(code, result=result) 
if result: 
    self.show_result(result) 

的問題是:如何show_result可以顯示在代碼中的異常引起的追溯?

ExecutionResult的error_before_execerror_in_exec ivars似乎都沒有提供對回溯的引用。同樣,sysshell.user_ns.namespace.get('sys')都沒有sys.exc_traceback屬性。

任何想法?謝謝!

愛德華

回答

0

IPython/core/interactiveshell.py包含InteractiveShell._showtraceback

def _showtraceback(self, etype, evalue, stb): 
    """Actually show a traceback. Subclasses may override...""" 
    print(self.InteractiveTB.stb2text(stb), file=io.stdout) 

的解決方案是猴補丁IS._showtraceback使得它寫入sys.stdout來(Qt的控制檯):

from __future__ import print_function 
... 
shell = self.kernelApp.shell # ZMQInteractiveShell 
code = compile(script, file_name, 'exec') 

def show_traceback(etype, evalue, stb, shell=shell): 
    print(shell.InteractiveTB.stb2text(stb), file=sys.stderr) 
    sys.stderr.flush() # <==== Oh, so important 

old_show = getattr(shell, '_showtraceback', None) 
shell._showtraceback = show_traceback 
shell.run_code(code) 
if old_show: shell._showtraceback = old_show 

注意:沒有必要將一個ExecutionResult對象傳遞給shell.run_code()。

EKR