Skip to content

Instantly share code, notes, and snippets.

@kezzico
Last active October 30, 2023 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kezzico/a16ebbee1573c3a177165e5c789fb141 to your computer and use it in GitHub Desktop.
Save kezzico/a16ebbee1573c3a177165e5c789fb141 to your computer and use it in GitHub Desktop.
Python: Setup a Virtual Environment

Python: Virtual Environments

A virtual environment is a sandbox for packages. Pip's default behavior is system level. However, packages installed in different virtual environment do not co-mingle. The ideal is for each project to have its own distinct virtual environment.

This is especially important on team projects. The virtual environment provides a means to a standard for packages. Identifying project dependencies and which package versions have already been tested against the code.

HOWTO:

It is common to see virtual environments named after the project it represents. The virtual enviromment in this sample will be called venv.

From a command shell. Set the Working Directory to the project's.

python can be used to create a new virtual environment by pasing the -m parameter

python -m venv venv

Once present, another step is necessary to activate the virtual environment.

Activate the virtual environment on Mac or Linux.

source ./venv/bin/activate

For Windows

./venv/bin/activate

It's not safe to install new packages, or run your Python script,

Troubleshooting Tips

  • Ensure python is in your path with which python

  • Mac users with Xcode, try python3 and pip3.

Sharing The Environment

To save your virtual environment's pips; Create a requirements.txt. pip can create a requirements.txt by redirecting the output from pip freeze to requirements.txt

pip freeze > requirements.txt

If the project uses source control, it is best not to add the venv directory. Including the requirements.txt is adequate.

git add requirements.txt

Regenerate the Environment

When joining a project already in progress. After git clone finishes. Check if there is a requirements.txt in the project's source code, pip can be used to regenerate the venv directory. To do this use pip install with the -r

pip install -r requirements.txt

All of the requirements will be downloaded and a new virtual environment will be created for you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment