【问题标题】:How to enable python repl autocomplete and still allow new line tabs如何启用 python repl 自动完成并仍然允许换行符
【发布时间】:2014-10-15 14:21:33
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • This HN comment 有一些代码可以在当前行仅包含空格时禁用自动完成。

标签: python shell scripting read-eval-print-loop


【解决方案1】:

您应该只使用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)

【讨论】:

  • 这是一种可能性,我经常使用它,但并非总是可以在您正在使用的每个平台/服务器上安装 IPython。我(和 OP)想知道是否可以调整标准 Python 解释器提示以在从空行开始时插入选项卡。
  • @MattDMo 我已经编辑了我的答案,以便在标准 python 解释器上添加一种方法。
  • 我发现除了 IPython 之外,我还需要安装 pyreadline 才能让标签完成现在工作。
猜你喜欢
  • 1970-01-01
  • 2014-08-27
  • 1970-01-01
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
  • 2016-05-11
  • 2012-05-09
  • 2017-08-29
相关资源
最近更新 更多