如何禁用 Python 3.4 中的新历史功能?

Lek*_*eyn 13 python interactive

升级到 Python 3.4 后,所有交互式命令都记录到~/.python_history. 我不希望 Python 创建或写入此文件。

创建符号链接/dev/null不起作用,Python 删除文件并重新创建它。该文件建议删除sys.__interactivehook__,而且,这还将删除制表完成。应该怎么做才能禁用写入此历史文件但仍保留制表符完成功能?

额外细节:

小智 8

另一个 ~/.pythonrc 解决方案:

import readline
readline.write_history_file = lambda *args: None
Run Code Online (Sandbox Code Playgroud)


Col*_*son 8

从 Python 3.6 开始,您可以使用readline.set_auto_history来禁用它:

import readline
readline.set_auto_history(False)
Run Code Online (Sandbox Code Playgroud)

  • 不起作用。这不会停止保存文件,而是在会话期间破坏历史记录。无论如何,Python 会在您下次运行它时默默地将“功能”重新打开。 (2认同)

cuo*_*glm 6

这对我有用。

创建~/.pythonrc文件:

import os
import atexit
import readline

readline_history_file = os.path.join(os.path.expanduser('~'), '.python_history')
try:
    readline.read_history_file(readline_history_file)
except IOError:
    pass

readline.set_history_length(0)
atexit.register(readline.write_history_file, readline_history_file)
Run Code Online (Sandbox Code Playgroud)

然后导出:

export PYTHONSTARTUP=~/.pythonrc
Run Code Online (Sandbox Code Playgroud)

  • 这仍然会导致写入 `~/.python_history`(使用 `PYTHONSTARTUP=$HOME/.pythonrc strace -e file,write -o /tmp/st python` 验证)。我开始认为没有办法禁用它,但保持制表符完成而不复制来自`/usr/lib/python3.4/site.py`的代码。 (2认同)

Lek*_*eyn 2

要防止 Python 写入~/.python_history,请禁用激活此功能的钩子:

import sys
# Disable history (...but also auto-completion :/ )
if hasattr(sys, '__interactivehook__'):
    del sys.__interactivehook__
Run Code Online (Sandbox Code Playgroud)

如果您想启用制表符补全并禁用历史记录功能,您可以调整代码site.enablerlcompleter。将以下代码写入~/.pythonrcexport PYTHONSTARTUP=~/.pythonrc在 shell 中进行设置以启用它。

import sys
def register_readline_completion():
    # rlcompleter must be loaded for Python-specific completion
    try: import readline, rlcompleter
    except ImportError: return
    # Enable tab-completion
    readline_doc = getattr(readline, '__doc__', '')
    if readline_doc is not None and 'libedit' in readline_doc:
        readline.parse_and_bind('bind ^I rl_complete')
    else:
        readline.parse_and_bind('tab: complete')
sys.__interactivehook__ = register_readline_completion
Run Code Online (Sandbox Code Playgroud)