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

2024-03-27

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

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

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

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

这是否可以直接在~/.pythonrc?


你应该只使用IPython http://ipython.org/。它具有制表符补全功能以及 for 循环或函数定义的自动缩进功能。例如:

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

要安装它,您可以使用pip:

pip install ipython

如果你没有pip安装后,您可以按照以下说明进行操作这一页 http://pip.readthedocs.org/en/latest/installing.html。在 python >= 3.4 上,pip默认安装。

如果你在 Windows 上,这一页 http://www.lfd.uci.edu/~gohlke/pythonlibs/#ipython包含 ipython 的安装程序(以及许多其他可能难以安装的 python 库)。


然而,如果由于任何原因你无法安装 ipython,Brandon Invergo 有创建一个python启动脚本 http://brandon.invergo.net/news/2014-03-21-Enhancing-the-Python-interpreter-with-a-start-up-script.html它为 python 解释器添加了一些功能,其中包括自动缩进。他已经在 GPL v3 下发布了它并发布了源代码here https://gitorious.org/bi-scripts/python-startup.

我复制了下面处理自动缩进的代码。我必须添加indent = ''在第 11 行,使其在我的 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐