Ubuntu16.04中Python3.5虚拟环境如何开启持久命令历史?
Hey there! I’ve dealt with this exact frustration before—losing your Python shell command history every time you exit a virtualenv is such a pain, especially when the system’s default Python works flawlessly. Let’s get this sorted out for your Python 3.5 venv.
The Root Cause
The system-wide Python automatically uses a history file (~/.python_history) thanks to default startup configurations that virtualenvs don’t inherit by default. We just need to manually wire up that same behavior for your virtual environment.
Step 1: Create a Python Startup Script
First, we’ll make a small script that tells Python to read and write command history. Create a file named ~/.python_startup.py with the following content:
import readline import os import atexit # Define the path to your history file (we'll reuse the system's default location) history_path = os.path.expanduser("~/.python_history") # Load existing history if the file exists try: readline.read_history_file(history_path) # Set how many commands to keep (adjust this number as you like) readline.set_history_length(1000) except FileNotFoundError: # If the file doesn't exist yet, no problem—we'll create it on exit pass # Save history when the Python shell exits atexit.register(readline.write_history_file, history_path)
Step 2: Make the Virtualenv Use This Script
You have two options here—choose whichever fits your workflow better:
Option A: Temporary (Per Session) Fix
Every time you activate your virtualenv, run this command to set the environment variable that tells Python to load our startup script:
export PYTHONSTARTUP=~/.python_startup.py
After running this, launch python3 in the venv, run some commands, exit, and re-open—your history should now persist.
Option B: Permanent (Auto-Load) Fix
To avoid running that export command every time, edit your virtualenv’s activate script:
- Navigate to your virtualenv’s directory (e.g.,
cd ~/my_python35_venv/bin) - Open the
activatefile in a text editor (like nano or vim) - Scroll to the very end of the file and add this line:
export PYTHONSTARTUP=~/.python_startup.py - Save and close the file.
Now, every time you activate your virtualenv with source ~/my_python35_venv/bin/activate, the PYTHONSTARTUP variable will be set automatically, and your command history will persist across sessions.
Verify It Works
Activate your virtualenv, launch python3, run a few test commands (like print("Hello History!")), exit the shell, and re-launch python3. Press the up arrow—your previous commands should show up!
Note: If ~/.python_history doesn’t exist yet, it will be created automatically the first time you exit the Python shell after setting up the script.
内容的提问来源于stack exchange,提问作者Jason

