What is Pyenv?
Pyenv is a Python version management tool that allows you to:
- Install multiple versions of Python.
- Easily switch between different Python versions.
- Set a global or local Python version for specific projects.
- Work with virtual environments efficiently.
Unlike system-installed Python, Pyenv lets you work with isolated Python versions without interfering with system dependencies.
Installing Pyenv on macOS
Step 1: Install Homebrew (if not installed)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Step 2: Install Pyenv
brew update
brew install pyenv
Step 3: Configure Shell for Pyenv
Add the following to your shell configuration file (~/.zshrc or ~/.bashrc)
:
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(pyenv init --path)"' >> ~/.zshrc
source ~/.zshrc
Step 4: Verify Installation
pyenv --version
Installing Pyenv on Windows
On Windows, you should use Pyenv for Windows, which is a separate fork.
Step 1: Install Pyenv for Windows
Download and install pyenv-win using PowerShell:
winget install pyenv-win
Step 2: Configure Environment Variables
Manually add the following paths to your system Environment Variables:
C:\Users\YourUser\.pyenv\pyenv-win\bin
C:\Users\YourUser\.pyenv\pyenv-win\shims
Step 3: Verify Installation
pyenv --version
Commonly Used Pyenv Commands
1. List all available versions
pyenv install --list
2. Install a Specific Python Version
pyenv install 3.10.4
3. List All Available Python Versions
pyenv install --list
4. Set a Global Python Version (Used across all projects)
pyenv global 3.10.4
5. Set a Local Python Version (For a specific project)
cd my_project
pyenv local 3.9.7
6. Show the Current Python Version
pyenv version
7. Uninstall a Python Version
pyenv uninstall 3.9.7
8. Update Pyenv
pyenv update
9. List All Installed Python Versions
pyenv versions
10. List all available virtual envs
pyenv virtualenvs
11. Create a virtualenv using pyenv
pyenv virtualenv 3.10.0 myenv
12. Activate a virtualenv
pyenv activate myenv
13. Rehash Pyenv (Necessary After Installing New Versions)
pyenv rehash
14. Uninstall Pyenv (If Needed)
For macOS:
brew uninstall pyenv
rm -rf ~/.pyenv
For Windows:
winget uninstall pyenv-win
Conclusion
Pyenv is an essential tool for developers working with multiple Python versions. By following the steps in this guide, you can easily configure and use Pyenv on both Windows and macOS. Whether you are switching Python versions, setting up project-specific environments, or ensuring compatibility, Pyenv simplifies Python version management. Start using Pyenv today and take full control of your Python development workflow! 🚀