如何启用python repl autocomplete并仍然允许新的行选项卡

2024-05-12 22:16:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前在~/.pythonrc中有以下功能,可以在python repl中启用自动完成:

# Autocompletion
import rlcompleter, readline
readline.parse_and_bind('tab:complete')

但是,当我从新行的开头(例如,在for循环的内部)开始tab时,我得到的是建议列表,而不是tab

理想情况下,我只希望在非空白字符之后获得建议。

这在~/.pythonrc中实现简单吗?


Tags: andimport功能列表forreadlineparsebind
1条回答
网友
1楼 · 发布于 2024-05-12 22:16:11

你应该用IPython。它同时具有for循环或函数定义的制表符完成和自动缩进功能。例如:

# Ipython prompt
In [1]: def stuff(x):
   ...:     |
#           ^ cursor automatically moves to this position

要安装它,可以使用pip

pip install ipython

如果没有安装pip,可以按照this page上的说明操作。在python>;=3.4上,pip默认安装。

如果您在windows上,this page包含ipython的安装程序(以及许多其他可能难以安装的python库)。


但是,如果由于任何原因无法安装ipython,Brandon Invergo有created a python start-up script为python解释器添加了一些特性,其中包括自动缩进。他在GPL v3下发布了它,并发布了源代码here

我已经复制了下面处理自动缩进的代码。我必须在第11行添加indent = '',才能使它在python 3.4解释器上工作。

import readline

def rl_autoindent():
    """Auto-indent upon typing a new line according to the contents of the
    previous line.  This function will be used as Readline's
    pre-input-hook.

    """
    hist_len = readline.get_current_history_length()
    last_input = readline.get_history_item(hist_len)
    indent = ''
    try:
        last_indent_index = last_input.rindex("    ")
    except:
        last_indent = 0
    else:
        last_indent = int(last_indent_index / 4) + 1
    if len(last_input.strip()) > 1:
        if last_input.count("(") > last_input.count(")"):
            indent = ''.join(["    " for n in range(last_indent + 2)])
        elif last_input.count(")") > last_input.count("("):
            indent = ''.join(["    " for n in range(last_indent - 1)])
        elif last_input.count("[") > last_input.count("]"):
            indent = ''.join(["    " for n in range(last_indent + 2)])
        elif last_input.count("]") > last_input.count("["):
            indent = ''.join(["    " for n in range(last_indent - 1)])
        elif last_input.count("{") > last_input.count("}"):
            indent = ''.join(["    " for n in range(last_indent + 2)])
        elif last_input.count("}") > last_input.count("{"):
            indent = ''.join(["    " for n in range(last_indent - 1)])
        elif last_input[-1] == ":":
            indent = ''.join(["    " for n in range(last_indent + 1)])
        else:
            indent = ''.join(["    " for n in range(last_indent)])
    readline.insert_text(indent)

readline.set_pre_input_hook(rl_autoindent)

相关问题 更多 >