【发布时间】:2012-09-02 07:03:39
【问题描述】:
有没有办法告诉交互式 Python shell 保留会话之间执行命令的历史记录?
在会话运行时,在执行命令后,我可以向上箭头并访问所述命令,我只是想知道是否有某种方法可以保存一定数量的这些命令,直到我下次使用Python shell。
这将非常有用,因为我发现自己在会话中重复使用了在上次会话结束时使用的命令。
【问题讨论】:
标签: python linux python-2.7
有没有办法告诉交互式 Python shell 保留会话之间执行命令的历史记录?
在会话运行时,在执行命令后,我可以向上箭头并访问所述命令,我只是想知道是否有某种方法可以保存一定数量的这些命令,直到我下次使用Python shell。
这将非常有用,因为我发现自己在会话中重复使用了在上次会话结束时使用的命令。
【问题讨论】:
标签: python linux python-2.7
在使用virtual environment 时,这对于 Python 3 也是必需的。
我使用一个稍微不同的版本,它为每个虚拟环境保留一个历史文件:
import sys
if sys.version_info >= (3, 0) and hasattr(sys, 'real_prefix'): # in a VirtualEnv
import atexit, os, readline, sys
PYTHON_HISTORY_FILE = os.path.join(os.environ['VIRTUAL_ENV'], '.python_history')
if os.path.exists(PYTHON_HISTORY_FILE):
readline.read_history_file(PYTHON_HISTORY_FILE)
atexit.register(readline.write_history_file, PYTHON_HISTORY_FILE)
【讨论】:
当然可以,只需一个小的启动脚本。来自python教程中的Interactive Input Editing and History Substitution:
# 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:
现在在支持
readline的系统上的交互式解释器中默认启用制表符补全。默认情况下也启用历史记录,并写入(和读取)文件~/.python-history。
【讨论】:
.pyhistory文件的位置改为虚拟环境文件夹,而不是用户主文件夹。
使用IPython。
无论如何,你应该这样做,因为它太棒了:持久的命令历史记录只是它比普通 Python shell 更好的众多方式之一。
【讨论】: