2013-11-03 39 views
14

您可以在腳本中使用下面的代碼啓動交互式控制檯:鍵盤快捷鍵斷裂從腳本運行交互式Python控制檯

import code 

# do something here 

vars = globals() 
vars.update(locals()) 
shell = code.InteractiveConsole(vars) 
shell.interact() 

當我運行像這樣的腳本:

$ python my_script.py 

的交互式控制檯打開:

Python 2.7.2+ (default, Jul 20 2012, 22:12:53) 
[GCC 4.6.1] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
(InteractiveConsole) 
>>> 

控制檯已加載所有全局和本地語言,因爲我可以輕鬆測試。

這裏的問題是,在開始的Python控制檯時箭不,因爲他們通常做的工作。他們只是顯示轉義字符到控制檯:

>>> ^[[A^[[B^[[C^[[D 

這意味着我不能使用上/下箭頭鍵調用以前的命令,我也不能編輯與左/右箭頭鍵的線條。

有誰知道這是爲什麼和/或如何避免呢?

+2

要從代碼運行IPython的殼:'從IPython的進口嵌入;嵌入()'(變量透明傳遞,包括當地人)。 – jfs

回答

33

退房readlinerlcompleter

import code 
import readline 
import rlcompleter 

# do something here 

vars = globals() 
vars.update(locals()) 
readline.set_completer(rlcompleter.Completer(vars).complete) 
readline.parse_and_bind("tab: complete") 
shell = code.InteractiveConsole(vars) 
shell.interact() 
+1

如果我可以,我願意給你個大獎:)短而精確的最佳答案:) – ducin

+0

由於'不包含在Windows readline','pyreadline'可以用來使這個解決方案的工作;只需安裝'pyreadline'並在導入'readline'之前導入它。 –

+0

你可能需要另一名比'vars'雖然,以免覆蓋內置'vars'功能。 – csl

2

這是我使用的一個:

def debug_breakpoint(): 
    """ 
    Python debug breakpoint. 
    """ 
    from code import InteractiveConsole 
    from inspect import currentframe 
    try: 
     import readline # noqa 
    except ImportError: 
     pass 

    caller = currentframe().f_back 

    env = {} 
    env.update(caller.f_globals) 
    env.update(caller.f_locals) 

    shell = InteractiveConsole(env) 
    shell.interact(
     '* Break: {} ::: Line {}\n' 
     '* Continue with Ctrl+D...'.format(
      caller.f_code.co_filename, caller.f_lineno 
     ) 
    ) 

例如,請考慮下面的腳本:

a = 10 
b = 20 
c = 'Hello' 

debug_breakpoint() 

a = 20 
b = c 
c = a 

mylist = [a, b, c] 

debug_breakpoint() 


def bar(): 
    a = '1_one' 
    b = '2+2' 
    debug_breakpoint() 

bar() 

執行時,該文件顯示爲以下行爲:

$ python test_debug.py 
* Break: test_debug.py ::: Line 24 
* Continue with Ctrl+D... 
>>> a 
10 
>>> 
* Break: test_debug.py ::: Line 32 
* Continue with Ctrl+D... 
>>> b 
'Hello' 
>>> mylist 
[20, 'Hello', 20] 
>>> mylist.append(a) 
>>> 
* Break: test_debug.py ::: Line 38 
* Continue with Ctrl+D... 
>>> a 
'1_one' 
>>> mylist 
[20, 'Hello', 20, 20]