python - 给 Python 终端一个持久的历史

标签 python linux python-2.7

有没有办法告诉交互式 Python shell 保留 session 之间执行命令的历史记录?

在 session 运行时,在执行命令后,我可以向上箭头并访问所述命令,我只是想知道是否有某种方法可以保存一定数量的这些命令,直到我下次使用Python shell。

这将非常有用,因为我发现自己在 session 中重复使用了在上次 session 结束时使用的命令。

最佳答案

当然可以,只需一个小的启动脚本。来自 Interactive Input Editing and History Substitution在python教程中:

# 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=~/.pystartup" in bash.

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

从 Python 3.4 开始,the interactive interpreter supports autocompletion and history out of the box :

Tab-completion is now enabled by default in the interactive interpreter on systems that support readline. History is also enabled by default, and is written to (and read from) the file ~/.python-history.

关于python - 给 Python 终端一个持久的历史,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12334316/

相关文章:

python - 从现有的阻塞代码重构扭曲的 tcp 客户端

python - 将时间转换为纪元(Python)

linux - ld: 找不到....在集群中编译 CAMB 时出错(ifort 编译器)

c++ - 64 位 Linux 上的链接不正确

python - 我的 Python 安装应使用哪个版本的 Pip?

python - 导入错误: No module named enum

python - 在谷歌中使用 unicode 从 python 脚本翻译 url

javascript - 如何在 python 中使用 selenium 驱动程序单击链接而不知道 anchor 标记内的文本

python - 直观表示 X 和 Y 值

linux - 如何将txt文件追加到之前创建的最后一行