My Digital Garden

Python Virtual Environment

Python Virtual Environment

Virtual Environments in Pyuthion are a mechanism that allow you to create independent collections of python packages for a specific project:

each with their own independent set of Python packages installed in their site directories. A virtual environment is created on top of an existing Python installation, known as the virtual environment’s “base” Python, and may optionally be isolated from the packages in the base environment, so only those explicitly installed in the virtual environment are available.

When used from within a virtual environment, common installation tools such as pip will install Python packages into a virtual environment without needing to be told to do so explicitly.

Working with virtual environments

  • to create a new virtual environment, go the folder within which you want the environment folder created, and use this command:

    python -m venv <environment-name>

  • to activate a virtual environment, from inside the environment folder run Scripts\activate

    the terminal prompt will change to show (<environment-name) as part of the prompt

  • to install packages into an activated virtual environment, use:

    python -m pip install <package-name>

  • to deactivate a virtual environment, run deactivate

    • After executing the deactivate command, your command prompt returns to normal. This change means that you’ve exited your virtual environment. If you interact with Python or pip now, you’ll interact with your globally configured Python environment.
  • do not check your virtual environment into version control, as the pyenv.cfg file contains machine-specific paths

    • create virtual environments either in a separate part of your directory tree, outside the project root, or in a folder within your project that is ignored in .gitignore

    • to transfer configuration to other users of your project, once you have activated and configured your virtual environment, run

      python -m pip freeze > requirements.txt

      from your project root directory, and check requirements.txt into source control

    • to configure a new, activated, virtual environment from a requirements.txt file, use the command

      python -m pip install -r requirements.txt

See also