Some versions of the Python interpreter support editing of the current input line and history substitution, similar to facilities found in the Korn shell and the GNU Bash shell. This is implemented using the GNU Readline library, which supports Emacs-style and vi-style editing. This library has its own documentation which I won’t duplicate here; however, the basics are easily explained. The interactive editing and history described here are optionally available in the Unix and Cygwin versions of the interpreter.
一些版本的Python解释器支持对当前输入行和历史记录的编辑,就像Korn Shell和GNU Bash Shell提供的工具一样。 这是使用支持Emacs风格和VI风格的 GNU Readline 库实现的。 这个库包含自己的文档,这里我就不列出了,但最基本的用法是很容易理解的。 这里描述的交互编辑和历史记录功能在Unix和Cygwin版本的解释器中都是可选的有效功能。
This chapter does not document the editing facilities of Mark Hammond’s PythonWin package or the Tk-based environment, IDLE, distributed with Python. The command line history recall which operates within DOS boxes on NT and some other DOS and Windows flavors is yet another beast.
本章 不 包括Mark Hammond编写的PythonWin包中编辑功能或Python携带的基于Tk的IDLE环境的文档。 在NT上的DOS窗口或其他DOS中,以及Windows系列系统上,命令行历史记录是糟糕的。
If supported, input line editing is active whenever the interpreter prints a primary or secondary prompt. The current line can be edited using the conventional Emacs control characters. The most important of these are: C-A (Control-A) moves the cursor to the beginning of the line, C-E to the end, C-B moves it one position to the left, C-F to the right. Backspace erases the character to the left of the cursor, C-D the character to its right. C-K kills (erases) the rest of the line to the right of the cursor, C-Y yanks back the last killed string. C-underscore undoes the last change you made; it can be repeated for cumulative effect.
如果支持的话,输入行编辑功能在解释器中总是可用的。 当前行可以使用常见的Emacs控制字符进行编辑。 最重要的一些包括: C-A (Control-A),将光标移动到左边; C-F ,将光标移动到右边; :kdb:`C-K` ,删除行中光标右边的内容; :kdb:`C-Y` ,删除行中光标左边的内容; :kdb:`C-underscore` ,撤销最后的编辑修改,可以重复撤销。
History substitution works as follows. All non-empty input lines issued are saved in a history buffer, and when a new prompt is given you are positioned on a new line at the bottom of this buffer. C-P moves one line up (back) in the history buffer, C-N moves one down. Any line in the history buffer can be edited; an asterisk appears in front of the prompt to mark a line as modified. Pressing the Return key passes the current line to the interpreter. C-R starts an incremental reverse search; C-S starts a forward search.
历史记录按照如下方式工作: 所有非空的输入行都会被存储在一个历史缓冲区内,当一个新提示符出现时,你被置于这个缓冲区底部的一个新行上。 使用 C-P 可以在这个历史缓冲区内向上(往后)移动一行,而 C-N 是向下(往前)移动一行。 历史缓冲区内的任何行都是可编辑的,当对某行作编辑后就会在提示符前面显示一个星号(*)来标示。 按下 Return 键就可以将当前行传递给Python解释器。
The key bindings and some other parameters of the Readline library can be customized by placing commands in an initialization file called ~/.inputrc. Key bindings have the form
key-name: function-name
or
"string": function-name
and options can be set with
set option-name value
关于Readline库的键绑定和一些其他参数可以在一个叫做 ~/.inputrc 的初始化文件中通过放置命令自定义。 键绑定的书写格式是:
key-name: function-name
或者:
"string": function-name
并且可以通过如下方式设定选项:
set option-name value
For example:
例如:
# I prefer vi-style editing:
set editing-mode vi
# Edit using a single line:
set horizontal-scroll-mode On
# Rebind some keys:
Meta-h: backward-kill-word
"\C-u": universal-argument
"\C-x\C-r": re-read-init-file
Note that the default binding for Tab in Python is to insert a Tab character instead of Readline’s default filename completion function. If you insist, you can override this by putting
Tab: complete
in your ~/.inputrc. (Of course, this makes it harder to type indented continuation lines if you’re accustomed to using Tab for that purpose.)
注意:在Python中, Tab 默认绑定为插入一个 Tab 字符代替Readline的默认文件名补全函数。 如果你较真,你可以通过在 ~/.inputrc 文件中加入以下键绑定覆盖它。
Tab: complete
(当然,如果你已经习惯使用 Tab 来补全文件名,这会让输入缩进延续行变得困难。)
Automatic completion of variable and module names is optionally available. To enable it in the interpreter’s interactive mode, add the following to your startup file:
对于变量和模块名也可以使用自动补全。 想要在解释器的交互模式中使用它,你需要在启动文件中添加以下代码: [1]
import rlcompleter, readline
readline.parse_and_bind('tab: complete')
This binds the Tab key to the completion function, so hitting the Tab key twice suggests completions; it looks at Python statement names, the current local variables, and the available module names. For dotted expressions such as string.a, it will evaluate the expression up to the final '.' and then suggest completions from the attributes of the resulting object. Note that this may execute application-defined code if an object with a __getattr__() method is part of the expression.
这会把 Tab 键绑定到补全函数上,所以当敲击两次 Tab 键时就会提示补全字符。 它会查看Python声明的名称,当前局部变量和有效的模块名。 对于类似 string.a 的点号表示,它将这个表示看作最后的 '.' 并且从结果对象的属性中给出补全建议。 注意:如果一个带有 __getattr__() 方法的对象是这个表示的一部分,这可能会执行程序定义代码。
A more capable startup file might look like this example. Note that this deletes the names it creates once they are no longer needed; this is done since the startup file is executed in the same namespace as the interactive commands, and removing the names avoids creating side effects in the interactive environment. You may find it convenient to keep some of the imported modules, such as os, which turn out to be needed in most sessions with the interpreter.
一个更有效的启动文件看上去可能类似这个示例。 注意:由这个文件创建的名称一旦不再需要就会被删除; 在同一个命名空间中,像交互命令,从启动文件被执行时就会完成这些绑定,并且通过删除名称来避免给交互环境带来副作用。 你可能会发现这对维持一些导入的模块很方便,像 os ,它们被证明在大多数解释器会话中是必须的。
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.
import atexit
import os
import readline
import rlcompleter
historyPath = os.path.expanduser("~/.pyhistory")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
This facility is an enormous step forward compared to earlier versions of the interpreter; however, some wishes are left: It would be nice if the proper indentation were suggested on continuation lines (the parser knows if an indent token is required next). The completion mechanism might use the interpreter’s symbol table. A command to check (or even suggest) matching parentheses, quotes, etc., would also be useful.
与更早的解释器版本相比,这个功能是一个庞大的步骤。 然而,一些要求被舍弃:如果在连续行中使用适当的缩进一切就OK了(当下一行要求一个缩进标记时,语法分析器知道如何处理)。 完整的结构可能使用解释器的table标志。 使用命令检查(或提示)匹配的圆括号,引号等也是很有用的。
Footnotes
| [1] | Python will execute the contents of a file identified by the PYTHONSTARTUP environment variable when you start an interactive interpreter. 当交互解释器启动时,Python会执行环境变量 PYTHONSTARTUP 定义的文件内容。 |