有没有办法告诉交互式 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/