Zen*_*nce 10 python shell scripting read-eval-print-loop
我目前有以下内容在~/.pythonrcpython repl中启用自动完成:
# Autocompletion
import rlcompleter, readline
readline.parse_and_bind('tab:complete')
Run Code Online (Sandbox Code Playgroud)
但是,当我tab从一个新行的开头(例如,在for循环的内部)时,我得到一个建议列表而不是一个tab.
理想情况下,我希望仅在非空格字符后获得建议.
这是直截了当地实现的~/.pythonrc吗?
par*_*ent 25
你应该只使用IPython.它具有Tab键完成和for循环或函数定义的自动缩进.例如:
# Ipython prompt
In [1]: def stuff(x):
...: |
# ^ cursor automatically moves to this position
Run Code Online (Sandbox Code Playgroud)
要安装它,您可以使用pip:
pip install ipython
Run Code Online (Sandbox Code Playgroud)
如果您尚未pip安装,则可以按照此页面上的说明进行操作.在python> = 3.4上,pip默认安装.
如果您在Windows上,此页面包含ipython(以及许多其他可能难以安装的python库)的安装程序.
但是,如果由于任何原因你无法安装ipython,Brandon Invergo 创建了一个python启动脚本,它为python解释器添加了几个功能,其中包括自动缩进.他已经在GPL v3下发布了它并在此发布了源代码.
我已经复制了下面处理自动缩进的代码.我必须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)
Run Code Online (Sandbox Code Playgroud)