键盘快捷键破坏了从脚本运行交互式Python控制台

时间:2013-11-03 15:14:49

标签: python shell

您可以使用以下代码从脚本内部启动交互式控制台:

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 个答案:

答案 0 :(得分: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 :(得分:1)

这是我使用的那个:

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]