Virtual environment (“virtualenv” or “venv”) is a self-contained directory that contains local Python interpreter along with a set of libraries, packages, and scripts. This setup allows you to isolate your Python project’s dependencies from those of other projects or the system’s global environment.
Using Virtual Environments Provides:
- Isolation: venv allows you to create isolated environments for Python projects
- Dependency Management: You can easily manage modules and install specific versions of packages for each project that prevents module update and change.
- Reproductability: You can share the environment configuration with others, allowing them to set up the exact same environment.
- Portability: You can easily transfer your project (such as to Docker ) along with its dependencies by sharing the virtual environment directory.
Create venv
You can create easily venv by using python.
- Create new Folder
- Open this new folder by IDE(VS Code, Pycharm …)
- Create new terminal
Run script below:
1 | python -m venv venv |
After runned script, python virtual environment folder(venv) is created.
Activate Venv
After virtual environment created, we need to activate.
Run script below inside of your venv folder exists.
1 | venv\Scripts\activate.bat |
If (venv) is appear it means your venv is active.
Dependencies
In Python, dependencies refer to external packages or modules that your code relies on to perform certain tasks or functions. These dependencies need to be installed in your Python environment in order for your code to run correctly.
In python usally dependencies stores in requirements.txt file.
In requirements.txt, Flask
and requests
are dependencies, and the version numbers (2.0.1
and 2.26.0
, respectively) specify the exact versions of these packages that your code requires.
Igonere venv
Adding venv folder and modules into git is not a sense way. We should add venv folder to .gitignore and we should define a requirements.txt file to easy deployment.
Create requirements.txt
Above, we defined two dependencies (Flask, requests). To create requirements.txt file that contains all modules installed run the script below:
1 | pip freeze > requirements.txt |
In the above, pip freeze command finds all external modules with spesific version and “> requirements.txt” command exports dependencies to file.
Set venv & dependencies from external Source
When we clone another code from external source (such as github). We cannot download venv file directly. We need to set up venv manually first. Then we need to download dependencies.
To download all dependencies after venv created run the script below:
1 | pip install -r requirements.txt |
This command downloads all dependencies from requirements.txt file and installs current virtual environment