Python 3出现(至少在默认情况下),以保持交互式命令的历史记录在全球位置~/.python_history
。结果,合并了在不同虚拟环境中发出的命令。
有没有办法隔离我的Python历史记录,以便每个虚拟环境都有(并访问)它自己的?
要实现这一点,您需要有一个PYTHONSTARTUP
文件。以下适用于我:
def init():
import os
# readline/pyreadline
try:
import readline
histfiles = ['~/.python_history']
if 'VIRTUAL_ENV' in os.environ:
histfiles.append('$VIRTUAL_ENV/.python_history')
for histfile in histfiles:
try:
histfile = os.path.expandvars(histfile)
histfile = os.path.expanduser(histfile)
readline.read_history_file(histfile)
except IOError:
pass # No such file
def savehist():
histsize = os.environ.get('HISTSIZE')
if histsize:
try:
histsize = int(histsize)
except ValueError:
pass
else:
readline.set_history_length(histsize)
histfile = histfiles[-1]
histfile = os.path.expandvars(histfile)
histfile = os.path.expanduser(histfile)
readline.write_history_file(histfile)
import atexit
atexit.register(savehist)
except (ImportError, AttributeError):
# no readline or atexit, or readline doesn't have
# {read,write}_history_file - ignore the error
pass
init()
del init
适应您的需求。请参阅我的完整init.py
(text version; https://git.phdru.name/dotfiles.git/的git存储库,请参阅文件lib/python/init.py
)。