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.