Skip to content

Instantly share code, notes, and snippets.

@ThingEngineer
Created January 24, 2025 20:25
Show Gist options
  • Save ThingEngineer/78e5b8f817ae32fd6167b88958727e26 to your computer and use it in GitHub Desktop.
Save ThingEngineer/78e5b8f817ae32fd6167b88958727e26 to your computer and use it in GitHub Desktop.
Python Virtual Environment Notes

Virtual Environments (bash) A virtual environment is an isolated Python environment that allows you to install packages without affecting other Python projects or your system's Python installation. It also ensures you are working in a clean slate environment and enables reproducibility through dependency tracking.

Create:

  • mdir my_project
  • python3 -m venv my_project

Use:

  • source my_project/bin/activate

Make reproducible: manage dependancies for deployment, sharing, etc.

  • cd my_project
  • pip install -U setuptools pip # Ensure up-to-date packaging tools
  • pip install pipreqs
  • mkdir src # Install your project's dependencies here (e.g., pip install requests numpy)

Generate dependency requirements:

  • pipreqs # Generates requirements.txt in the current directory (my_project/)

Stop using virtual env:

  • deactivate

Later, to install requirements (from within the project directory):

  • pip install -r requirements.txt

Now (while the virtual environment is active):

  • Running ‘python’ it will use python3 from the create step
  • Running ‘pip’ will use the correct version
  • All modules are installed inside this environment only
  • pipreqs generates requirements.txt based on the currently installed packages in the environment

Important: Commit the requirements.txt file to version control (e.g., Git) so others can easily recreate your project's environment.

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