Skip to content

Instantly share code, notes, and snippets.

@JetStarBlues
Last active April 26, 2021 19:56
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 JetStarBlues/dec526bb8e450b53bd27feb5480a0cf9 to your computer and use it in GitHub Desktop.
Save JetStarBlues/dec526bb8e450b53bd27feb5480a0cf9 to your computer and use it in GitHub Desktop.
Using virtualenv in Python3

Using virtualenv in Python3

By using virtualenv, can avoid installing modules globally

Installing virtualenv

  • pip install virtualenv

Creating a virtual environment

  • python -m venv env
    • Where second argument is the location to create the virtual environment... Typically this is a directory in the project named env
    • Said directory should be added to .gitignore

Activating a virtual environment

  • Unix

    • activate
      • source env/bin/activate
    • check if succesfully activated
      • which python
        • should point to env directory (.../env/bin/python)
  • Windows

    • Powershell
      • activate
        • .\env\bin\activateActivate.ps1
          • script will likely fail to run (if not running PS as admin) with message cannot be loaded because running scripts is disabled on this system. To workaround this, can change permissions of current Powershell session.
            • Set-ExecutionPolicy Unrestricted -Scope Process
      • check if sucessfully activated
        • where.exe python
          • should point to env directory (...\env\bin\python.exe)

Leaving the virtual environment

  • deactivate

Installing packages

  • pip install packageName

Installing packages using requirements file

  • pip install -r requirements.txt
    • where -r flag is equivalent to --requirement and tells pip that file argument is a requirements file

Freezing dependencies

  • pip freeze
    • export list of all installed packages and their versions

Sources:

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