如何启用python repl自动完成并仍然允许新行选项卡

时间:2014-08-21 20:05:21

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

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

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

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

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

~/.pythonrc

中实现这一点是否直截了当

1 个答案:

答案 0 :(得分:24)

您应该使用IPython。它具有Tab键完成和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)