pyenv设置全局Python版本未生效,如何为指定Shell及子Shell设置版本?
pyenv global & Setting Python Versions for Specific Shells First: Fix the pyenv global Issue
It sounds like your pyenv global 2.7 isn’t taking effect because pyenv might not be properly initialized in your shell. Let’s sort that out first:
Check if pyenv’s shims are prioritized in your PATH
Run this command to see your current PATH configuration:echo $PATHYou should see
$HOME/.pyenv/shimsat the very start of the output. If it’s missing or comes after your system’s Python path, that’s why the system’s Python 3.6.4 is being called instead of pyenv’s version.Add pyenv initialization to your shell config
Depending on your shell (bash, zsh, etc.), add these lines to your shell’s config file (like~/.bashrcfor bash,~/.zshrcfor zsh):export PATH="$HOME/.pyenv/bin:$PATH" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)"Save the file, then restart your shell or run
source ~/.bashrc(or the matching config file) to apply changes. Now runpyenv global 2.7again, andpython --versionshould show your desired 2.7 release.
Setting Python Versions for Specific Shells & Their Subshells
Now, if you want to target a specific shell session (and all its subshells) with a Python version, here are your go-to methods:
1. Temporary Session-Specific Setup (Current Shell + Subshells)
Use the pyenv shell command—it sets the PYENV_VERSION environment variable, which gets inherited by any subshells launched from the current session. This only lasts until you exit the shell or unset the variable.
Example:
# Set version for current shell and its subshells pyenv shell 2.7 # Verify it works python --version # Should show Python 2.7.x # Launch a subshell (e.g., bash) bash python --version # Still shows Python 2.7.x # Exit the subshell exit # Unset the session-specific version when done pyenv shell --unset
2. Permanent User-Specific Setup (All Shells for a User)
If you want every shell session for your user to use a specific Python version, confirm pyenv is properly initialized (as we fixed earlier), then run:
pyenv global <desired-version>
This sets the default version for all your shell sessions, and any subshells will inherit this setting too.
3. Directory-Specific Setup (Shells in a Folder + Subfolders)
If you want any shell that navigates into a specific directory (and its subdirectories) to use a certain Python version, use pyenv local. This creates a .python-version file in the directory, which pyenv reads automatically when you enter the folder. Subshells launched in this directory will also use the specified version.
Example:
# Navigate to your project folder cd ~/my-python-2.7-project # Set the local version pyenv local 2.7 # Verify python --version # Python 2.7.x # Launch a subshell here bash python --version # Still 2.7.x
内容的提问来源于stack exchange,提问作者Alexander Mills

