python-3.x

How to disable python history saving?


I am on linux (OpenSuse) machine using CPython with

22;~/.../XO/> python3 --version
Python 3.6.10

I would like to setup saving/loading python interactive shell history separately for each working directory in which a session has been started. I am trying to do it in /etc/pythonstart having export PYTHONSTARTUP=/etc/pythonstart

The relevant content of my /etc/pythonstart is

import os
import readline
import atexit

historyFile = ".pyhistory"
cwd         = os.getcwd()

historyPath = cwd + "/" + historyFile

def save_history():
    try:
        readline.write_history_file(historyPath)
    except:
        pass

# read history
if os.path.exists(historyPath):
    readline.set_history_length(100)
    readline.read_history_file(historyPath)

# save history
atexit.register(save_history)

It almost works, except python also saves and reads history in ~/.python_history and it gets merged for all sessions. Is there a way to disable the later behaviour and if yes, how?


Solution

  • This modification to the startup file does the job. It does not disable writing to ~/.python_history but ignores its content on startup.

    import atexit
    import os
    import readline
    
    historyFile = ".pyhistory"
    startFile   = ".pystart"
    cwd         = os.getcwd()
    
    historyPath = cwd + "/" + historyFile
    startPath   = cwd + "/" + startFile
    
    def save_history(historyPath=historyPath):
        import readline
        try:
            readline.write_history_file(historyPath)
            readline.clear_history()
        except:
            pass
    
    # ignore history loaded from the standard file
    readline.clear_history()
    
    # load history from the custom file
    if os.path.exists(historyPath):
        readline.set_history_length(100)
        readline.read_history_file(historyPath)
    
    # register handler
    atexit.register(save_history)