简体   繁体   English

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

[英]Keyboard shortcuts broken running interactive Python Console from a script

You can start an interactive console from inside a script with following code: 您可以使用以下代码从脚本内部启动交互式控制台:

import code

# do something here

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

When I run the script like so: 当我像这样运行脚本时:

$ python my_script.py

an interactive console opens: 交互式控制台打开:

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)
>>>

The console has all globals and locals loaded which is great since I can test stuff easily. 控制台有所有全局和本地加载,这很好,因为我可以轻松测试东西。

The problem here is that arrows don't work as they normally do when starting an Python console. 这里的问题是箭头在启动Python控制台时不像通常那样工作。 They simply display escaped characters to the console: 他们只是将转义字符显示到控制台:

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

This means that I can't recall previous commands using the up/down arrow keys and I can't edit the lines with the left/right arrow keys either. 这意味着我无法使用向上/向下箭头键调用以前的命令,也无法使用左/右箭头键编辑行。

Does anyone know why is that and/or how to avoid that? 有谁知道为什么会这样和/或如何避免这种情况?

Check out readline and rlcompleter : 查看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()

This is the one I use: 这是我使用的那个:

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
        )
    )

For example, consider the following script: 例如,请考虑以下脚本:

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()

When executed, this file shows to following behavior: 执行时,此文件显示以下行为:

$ 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM