Set up a Python virtual environment

From Parallel Library Services
Revision as of 18:48, 4 November 2021 by Simon (talk | contribs)
Jump to navigation Jump to search

Python virtual environments run their own site directories, allowing them to be optionally separated from system directories. This can easily avoid a potential nightmare of version conflicts - one piece of software on your system may require a certain version to run, while another make require a different one.

Create

venv is a tool that can be used to create an environment:

python3 -m venv venv

When this is run, venv creates the target directory (in this case venv), and any parent directories that don't exist yet. It also puts a pyvenv.cfg file with a home key that points to the installation of Python from where the command was run.

Activate

source venv/bin/activate

You will see the prompt change to something like this:

(venv)Username@Computer myfolder %

Use

Install dependencies within the new Python virtual environment, using pip, the default package manager for Unix-like systems such as Mac OS and Linux. Swap out the {packagename} for the package you want to install.

pip install {packagename}

Deactivate

To stop it, type:

deactivate

Close

Simply type

exit

Remove

To remove a Python virtual environment, first deactivate it. Then you can use rm to remove it.

rm -r venv

A more thorough method is to specify removal of the files and folders made when the environment was created. In the folder where the venv is, run

rm -r bin include lib lib64 pyvenv.cfg share