Overview
You can create a virtual environment of Python like nvm by installing pyenv and pipenv.
pyenv is the version manager of Python(β nvm).
pipenv is the library manager of Python.
This manages installed libraries for each directories(projects) because the libraries installed via pipenv are installed in ~/.virtualenvs/<YOUR_DIRECTORY_NAME>-<UUID>
.
<YOUR_DIRECTORY_NAME>-<UUID>
directory is automatically generated when pipenv installs a library in the directory.
Getting started
1. Install pyenv
brew install pyenv
2. Add the paths to $PATH to be able to activate pyenv command and manage python versions with it
You need to add the following lines to .zprofile or .zshrc etc...
# Add .pyenv/bin to $PATH to be able to run pyenv command anywhere
export PATH="$HOME/.pyenv/bin:$PATH"
# Add .pyenv/shims to $PATH to switch python versions with pyenv command
eval "$(pyenv init -)"
How to manage your python virtualenvs with Pipenv
Pipenv Installation
Where does pipenv install a package (ja)
3. Install a python version
# Show the list of version available for installation
pyenv install -l
# Install the version
pyenv install <version> # ex: pyenv install 3.12.0
# Show the list of installed version
pyenv versions
4. Set the python version in the local directory
The python version is managed by .python-version
file created after the command.
# Set the version in local
pyenv local <version>
# Show the current python version
pyenv version
# Check whether python command is activated
python -V
5. Install pipenv
Pipfile (β package.json) is created after the installation command.
brew install pipenv
# Set the same python version as pyenv
pipenv --python <version>
6. Install a package and create a virtual environment
When a package is installed for the first time in your current directory, ~/.virtualenvs/<YOUR_DIRECTORY_NAME>-<UUID>
directory is created and then the package is installed there.
# Add the package information to **Pipfile** and **Pipfile.lock** (be created if it doesn't exist)
pipenv install <PACKAGE_NAME>
# Uninstall
pipenv uninstall <PACKAGE_NAME>
7. Activate a virtual environment
You need to enter the virtual environment created above to use the installed packages.
# Activate the local directory's environment
# You can exit from it by entering `exit` if you want do
pipenv shell
# Activate the environment and run a command
pipenv run <COMMAND> # pipenv run python main.py
pipenv run <COMMAND>
means to run pipenv shell
and then run <COMMAND>
.
Other commands
# Show the path of the virtual environment (directory)
pipenv --venv
# Remove the local virtual environment with the whole installed packages
pipenv --rm
Top comments (1)
Nice. Thank you very much.