Virtual Environment – Python venv

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.

  1. Create new Folder
  2. Open this new folder by IDE(VS Code, Pycharm …)
  3. Create new terminal

Run script below:

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.

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:

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:

This command downloads all dependencies from requirements.txt file and installs current virtual environment

ibrahim tunc
ibrahim tunc
Articles: 13

Leave a Reply

Your email address will not be published. Required fields are marked *