virtualenv is a tool to create isolated Python environments.
Since Python 3.3, a subset of virtualenv has been integrated into the standard library under the venv module. However, virtualenv contains more features that enables virtualenv management to be more faster, extendable, and flexible.
Here is using pip to install the virtualenv package,
$ pip install --user virtualenvThere are several more methods to install virtualenv, like using pipx, wheel, sdist, etc., please refer to the official documentation for more information.There are also details about the compatibility of virtualenv with differnet Python interpreters and OS environments.
Use the --help command,
$ virtualenv --helpyou can find out these rich flag options of virtualenv.
Run this command to create a virtual environment,
$ virtualenv testenvWhat's inside after the creation?
testenv
├── bin
│ ├── activate
│ ├── activate.csh
│ ├── activate.fish
│ ├── activate.nu
│ ├── activate.ps1
│ ├── activate_this.py
│ ├── deactivate.nu
│ ├── pip
│ ├── pip3
│ ├── pip-3.12
│ ├── pip3.12
│ ├── python -> /usr/bin/python3.12
│ ├── python3 -> python
│ ├── python3.12 -> python
│ ├── wheel
│ ├── wheel3
│ ├── wheel-3.12
│ └── wheel3.12
├── lib
│ └── python3.12
└── pyvenv.cfg
3 directories, 19 filesSource to activate the virtual environment,
$ source testenv/bin/activateYou may need to run different activation file based on your system.
To install or uninstall a single package, run
$ pip install <package-name>To install a list of Python packages in requirements.txt, run
$ pip install -r requirements.txtTo uninstall the Python package,
$ pip uninstall <package-name>Run the following command to deactivate the virtual environment,
$ deactivateRemoving the virtual environment is simple, just to remove the virtual environment directory.
$ rm -r testenvIf you have multiple Python versions installed, then you can use --python/-p option to specify the Python version when creating the virtual environment. For example,
$ virtualenv -p python3.10 testenv10$ virtualenv -p python3.11 testenv11$ virtualenv -p python3.12 testenv12Happy coding!