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。它同时具有for循环或函数定义的制表符完成和自动缩进功能。例如:
要安装它,可以使用
pip
:如果没有安装
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解释器上工作。相关问题 更多 >
编程相关推荐