如何在Python解释器中重复上一个命令?

155 投票
26 回答
193084 浏览
提问于 2025-04-16 07:40

我怎么重复上一个命令?通常用的按键:上箭头、Ctrl+上箭头、Alt+p都不管用,按下去会出现一些奇怪的字符。

(ve)[kakarukeys@localhost ve]$ python
Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32) 
[GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world"
hello world
>>> ^[[A
  File "<stdin>", line 1
    ^
SyntaxError: invalid syntax
>>> ^[[1;5A
  File "<stdin>", line 1
    [1;5A
    ^
SyntaxError: invalid syntax
>>> ^[p
  File "<stdin>", line 1
    p
    ^
SyntaxError: invalid syntax
>>> 

26 个回答

52

按下 Alt + p 可以查看之前输入的命令,按 Alt + n 则可以查看之后的命令。

这是默认的设置,你可以根据自己的喜好在选项中找到“配置 IDLE”来更改这些快捷键。

187

在IDLE里,先去选项(Options)-> 配置IDLE(Configure IDLE)-> 键位(Keys),然后找到历史下一个(history-next)和历史上一个(history-previous),可以在这里修改快捷键。

接着点击获取新键位(Get New Keys for Selection),这样你就可以选择你想要的任何键位组合了。

66

我使用以下方法在 Python 解释器中启用历史记录。

这是我的 .pythonstartup 文件。PYTHONSTARTUP 环境变量被设置为这个文件的路径。

# python startup file 
import readline 
import rlcompleter 
import atexit 
import os 
# tab completion 
readline.parse_and_bind('tab: complete') 
# history file 
histfile = os.path.join(os.environ['HOME'], '.pythonhistory') 
try: 
    readline.read_history_file(histfile) 
except IOError: 
    pass 
atexit.register(readline.write_history_file, histfile) 
del os, histfile, readline, rlcompleter

你需要安装 readline 和 rlcompleter 这两个模块才能启用这个功能。

想了解更多信息,可以查看这个链接: http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP

所需的模块:

  1. http://docs.python.org/library/readline.html
  2. http://docs.python.org/library/rlcompleter.html

撰写回答