Python Virtual Environments

Python virtual environments create a virtual installation of Python inside a project directory. Users can then install and manage Python packages for each project. This allows users to be able to install packages and modify their Python environment without fear of breaking packages installed in other environments.

Creating a Virtual Environment

To create a virtual environment using Python use the following command:

python -m venv <envname>

This command will create a folder called envname and place the virtual installation of Python inside that folder. So for example, say you wanted to create a new virtual environment called myenv, you would issue the following command:

python -m venv myenv

Activating and Deactivating a Virtual Environment

After creating a virtual environment, it needs to be activated before you can begin installing packages. Failing to do so will install packages locally to your home directory. To activate the environment, use the command:

source <envname>/bin/activate

Following our myenv example above, you would issue the command:

source myenv/bin/activate

To confirm that the environment has been activated, use the which command and ensure that it points to the Python interpreter inside the environment directory. To deactivate or leave the environment, run the command:


Installing Packages

Once the virtual environment has been installed and activated, packages can be installed normally with pip using the command: 

pip install <module>


Packages can also be installed from source using a script using the commands:

python build
python install