Built-in venv
Create virtual environment
python3 -m venv myenv
python3 -m venv ~/envs/project1
Activate
source myenv/bin/activate
myenv\Scripts\activate
Deactivate
deactivate
Install packages
pip install requests
pip install -r requirements.txt
Export dependencies
pip freeze > requirements.txt
Virtualenv (older tool)
Install
pip install virtualenv
Create environment
virtualenv myenv
virtualenv -p python3.9 myenv
Usage (same as venv)
source myenv/bin/activate
pip install package
deactivate
Conda
Install Miniconda
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
Create environment
conda create -n myenv python=3.9
conda create -n dataenv python=3.9 pandas numpy
Activate
conda activate myenv
Deactivate
conda deactivate
List environments
conda env list
conda info --envs
Remove environment
conda env remove -n myenv
Export environment
conda env export > environment.yml
Create from file
conda env create -f environment.yml
Pipenv
Install
pip install pipenv
Create environment & install
pipenv install requests
pipenv install --dev pytest
Activate shell
pipenv shell
Run command
pipenv run python script.py
Lock dependencies
pipenv lock
Poetry
Install
curl -sSL https://install.python-poetry.org | python3 -
New project
poetry new myproject
cd myproject
Init existing project
poetry init
Add dependency
poetry add requests
poetry add --dev pytest
Install dependencies
poetry install
Run scripts
poetry run python script.py
Best practices
Project structure
myproject/
├── venv/
├── src/
├── tests/
├── requirements.txt
└── README.md
requirements.txt
requests==2.28.1
pandas>=1.4.0,<2.0.0
numpy~=1.23.0
Multiple environments
python3 -m venv venv-dev
source venv-dev/bin/activate
pip install -r requirements-dev.txt
python3 -m venv venv-prod
source venv-prod/bin/activate
pip install -r requirements.txt
Common commands
pip install --upgrade pip
pip list
pip freeze
pip show requests
pip uninstall requests
pip install requests==2.28.1
pip install git+https://github.com/user/repo.git
Troubleshooting
ls -la venv/bin/activate
chmod +x venv/bin/activate
which python
python --version
pip cache purge
pip install --force-reinstall -r requirements.txt
pyenv (Python version management)
curl https://pyenv.run | bash
pyenv install --list
pyenv install 3.9.10
pyenv global 3.9.10
pyenv local 3.8.12
pyenv virtualenv 3.9.10 myproject
pyenv activate myproject
Quick reference
python3 -m venv venv && source venv/bin/activate
pip install -r requirements.txt
pip freeze > requirements.txt
deactivate
rm -rf venv