龙空技术网

如何为Python终端提供持久性历史记录,附解答问题

Python骇客 129

前言:

当前咱们对“python_history”大概比较着重,朋友们都想要知道一些“python_history”的相关文章。那么小编在网摘上网罗了一些对于“python_history””的相关文章,希望看官们能喜欢,我们一起来了解一下吧!

问题

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

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

这非常有用,因为我发现自己在会话中重用命令,这是我在上一个会话结束时使用的。

解决方案

当然你可以用一个小的启动脚本。

来自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 atexitimport osimport readlineimport 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开始,交互式解释器支持开箱即用的自动完成和历史记录:

现在,在支持的系统上的交互式解释器中默认启用Tab-completion readline。默认情况下也会启用历史记录,并将其写入(并从中读取)文件~/.python-history。

最后多说一句,小编是一名python开发工程师,这里有我自己整理了一套最新的python系统学习教程,包括从基础的python脚本到web开发、爬虫、数据分析、数据可视化、机器学习等。想要这些资料的可以关注小编,并在后台私信小编:“01”即可领取。

标签: #python_history