如何将我的Python历史记录限制为虚拟环境?

时间:2019-04-22 15:35:18

标签: python-3.x virtualenv

Python 3出现(至少默认情况下),以将交互式命令的历史记录保留在全局位置~/.python_history中。结果,在不同虚拟环境中发出的命令将被合并。

是否有一种方法可以隔离我的Python历史记录,以便每个虚拟环境都拥有(并访问)自己的Python?

1 个答案:

答案 0 :(得分:0)

要实现此目的,您需要拥有一个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.pytext version;位于https://git.phdru.name/dotfiles.git/的git存储库,请参阅文件lib/python/init.py)。