Python: How to create a virtual environment

A virtual environment is a self-contained directory that holds a Python interpreter and its associated libraries. It allows you to isolate…

Python: How to create a virtual environment
Photo by David Clode on Unsplash

A virtual environment is a self-contained directory that holds a Python interpreter and its associated libraries. It allows you to isolate your project’s dependencies from the system-wide Python installation, making it easier to manage different projects with different requirements.

Step 1: Install virtualenv

If you don’t have virtualenv installed, you can install it using pip, Python's package manager:

pip install virtualenv

Step 2: Create a Virtual Environment

Create a new directory for your project and navigate to it in your terminal:

mkdir my_project 
cd my_project

Create a virtual environment in the project directory:

virtualenv venv

This will create a directory named venv in your project folder, which will hold the virtual environment.

Step 3: Activate the Virtual Environment

  • On Windows:
venv\Scripts\activate
  • On macOS and Linux:
source venv/bin/activate

You’ll notice that your command prompt changes to indicate that the virtual environment is active. This means that any Python-related commands you run will use the Python interpreter and libraries within the virtual environment.

Step 4: Installing Packages

With the virtual environment active, you can install packages just like you would with the system-wide Python installation. For example, let’s install the requests package:

pip install requests

This package will be installed only within the virtual environment, keeping your system-wide Python environment clean.

Step 5: Using the Virtual Environment

You can now work on your project within the virtual environment. Create your Python files, install dependencies, and run your scripts just like you normally would.

Step 6: Deactivate the Virtual Environment

When you’re done working on your project, you can deactivate the virtual environment:

deactivate

This returns you to your system’s global Python environment.

Conclusion

Using virtual environments is a recommended practice when working on Python projects. It helps you manage dependencies, avoid conflicts, and keep your project’s environment isolated. By following this tutorial, you should now be able to create and use virtual environments for your Python projects.

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…