Skip to main content

Command Palette

Search for a command to run...

Using virtual environments in Python

Updated
2 min read
Using virtual environments in Python
C

Senior Data Engineer • Contractor / Freelancer • GCP & AWS Certified


title: "Using virtual environments in Python" seoTitle: "Python Virtual Environments: A Guide" seoDescription: "Learn how to use Python virtual environments to manage project dependencies effectively and avoid conflicts with this comprehensive guide" datePublished: Sun Jul 28 2024 20:14:25 GMT+0000 (Coordinated Universal Time) cuid: clz600vjp000909l8dbk8e9i2 slug: using-virtual-environments-in-python cover: https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/9_eMsFKGJiM/upload/e2c91d8eba015021565e0e3bae4bc359.jpeg tags: programming-blogs, python, virtual-environment


In my yesterday's post, we looked at the basics of installing packages in Python using pip.

The next immediate step is to learn about virtual environments. When you install packages with pip, they are added to your 'global' library.

However, if you have multiple Python projects on your machine, each with different package requirements and dependencies, managing these packages globally can become a complex task.

A solution to this problem is to use virtual environments. A virtual environment is a lightweight, isolated Python installation specific to each project (read: folder), with its own list of installed packages.

This way, Project A can use version 1.0 of CoolPythonModule while Project B uses version 2.0, without conflicts.

There are multiple tools for managing environments: conda or poetry also do that, but one of the simplest options is venv.

To create a virtual environment, use the following command:

python3 -m venv .venv

# This creates a virtual environment in the '.venv' folder inside the current working directory

You can now activate the virtual environment:

source .venv/bin/activate

The name of the virtual env is displayed next to your user name. You can now install and do everything you need in terms of packages - they will after only this virtual env.

If you'd like to deactivate it, you do:

deactivate

Don't know which Python interpreter you're using?

which python

This will show you the path of the active interpreter.

P.S. Activate/deactivate scripts can do interesting things like assigning an environment variable upon activation.

Found it useful? Subscribe to my Analytics newsletter at notjustsql.com.


Enjoyed this? Here are some related articles you might find useful:

More from this blog

D

Datawise: A blog on SQL, BigQuery, Analytics, Python Tips and Tricks

204 posts

Data Engineer with a passion for transforming complex data landscapes into insightful stories. Here on my blog, I share insights, challenges, and the ever-evolving dance of technology and business.