14

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

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

这意味着我无法使用向上/向下箭头键调用以前的命令,也无法使用向左/向右箭头键编辑行。

有谁知道这是为什么和/或如何避免这种情况?

4

2 回答 2

34

签出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()
于 2013-11-03T15:28:13.327 回答
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]
于 2015-02-10T03:31:07.030 回答