Venv
Virtual Environments (venv) in Python
Section titled “Virtual Environments (venv) in Python”A virtual environment is a tool that allows you to create an isolated space for your Python projects. This way, you can install specific dependencies for each project without affecting the rest of your system or your other projects.
Why use virtual environments?
Section titled “Why use virtual environments?”- Isolation: Each project can have its own package versions, avoiding conflicts.
- Organization: Keep your dependencies separate and your system clean.
- Reproducibility: Makes it easier to share your project with others, ensuring that everyone uses the same library versions.
How to create a virtual environment?
Section titled “How to create a virtual environment?”-
Open a terminal in your project folder.
-
Run the following command:
Ventana de terminal python -m venv venvThis will create a folder named
venv
with everything you need for your virtual environment.
How to activate the virtual environment?
Section titled “How to activate the virtual environment?”-
On Windows:
Ventana de terminal .\venv\Scripts\activate -
On macOS/Linux:
Ventana de terminal source venv/bin/activateWhen the environment is active, you will see the environment name at the beginning of the command line.
How to install packages in the environment?
Section titled “How to install packages in the environment?”With the environment activated, use pip
to install packages only in that environment:
pip install package_name
How to deactivate the virtual environment?
Section titled “How to deactivate the virtual environment?”When you are finished working, you can exit the environment with:
deactivate
Best practices
Section titled “Best practices”-
Use a virtual environment for each project.
-
Add the
venv
folder to your.gitignore
file if you use version control. -
Save your dependencies in a
requirements.txt
file with:Ventana de terminal pip freeze > requirements.txt
Summary
Section titled “Summary”- Virtual environments help you keep your projects organized and free from dependency conflicts.
- They are easy to create, activate, and use.
- They are an essential tool for any modern Python developer.
Ready to test? Create and activate your first virtual environment in your next project.