In my previous post I’ve shown, how to create virtual environments with conda. I also explained, why I recommend to work with virtual environments instead with the system interpreter solely. Alternatively to conda, we can also create such virtual environments with Python’s built-in
Creating virtual environments with
- Open a terminal and change the current working directory (
cd) to the location, where you want to install the virtual environment (e.g., the corresponding project folder).
- To create a virtual environment, e.g., called “my_test_venv”, type:
python -m venv my_test_venv
- We can activate the environment via:
- We can verify the activation by checking the currently used Python version:
- To deactivate an active virtual environment, simply type:
Use pip to manage and install packages. E.g., to check, which packages are already installed, use
Create virtual environments with a specific Python version
The major difference between Python- and conda-generated virtual environments is, that conda downloads and installs the specified Python version as a package into the created virtual environment, while
venv relies on the installed Python interpreter(s) on your machine. This means, that you need to install a specific Python version in advance, if you’d like to use it in a virtual environment.
So far I couldn’t figure out, how to specify the desired Python version in the
venv command. Here is a solution using the
- If not already done, first install the
virtualenvpackage into your base Python installation:
python -m pip install virtualenv
- To create a virtual environment using a specific Python version, type:
virtualenv --python=<PATH/TO/THE/LOCAL-PYTHON-INTERPRETER/> <PATH/THE/NEW/VENV/>
<PATH/TO/THE/LOCAL-PYTHON-INTERPRETER/>specifies the path to the local Python installation you’d like to use, e.g.,
<PATH/THE/NEW/VENV/>is the path to the location, where you’d like to install virtual environment.