DEV Community

loading...

Random Python Tutorials: Up and Running With virtualenv

George Roros
・2 min read

If you have ever managed multiple python projects on a single machine, you may have run into a problem where you have different projects using different versions of a particular package. You update the package for the latest project you are working on, you then switch back to an older project and BOOM, dependency errors, everyone's favorite.

In this article, I will be giving a brief intro to getting up and running with virtualenv on your system.

virtualenv is a tool used to create and manage multiple python environments, so that you don't have to worry about overlapping packages.

The tool works by creating a fresh python installation where you specify

1. Installing virtualenv

To install virtualenv via pip:

$ pip install virtualenv

Check your installation

$ virtualenv --version

2. Creating your first virtual environment with venv

Let's make a test_project/ folder to create our virtual environment in

$ mkdir test_project/
$ cd test_project/
$ virtualenv venv

The virtualenv command takes an argument, DEST_DIR, which is the directory in which your virtual environment will be created. We created our environment in venv if you do not specify a destination directory virtualenv will place the files in the current directory

to use the virtual environment it must be activated

$ source venv/bin/activate

if you used a name other than venv you should substitute it in the above command (ex: source [folder_name]/bin/activate).

you should see (venv) in front of your default shell.

now that we have activated our virtual environment let's install a package using pip

$ pip install requests

now run:

$ pip freeze

you should see the requests package is installed.

certifi==2019.9.11
chardet==3.0.4
idna==2.8
requests==2.22.0
urllib3==1.25.3

now let's deactivate the virtual environment and check the installed packages

$ deactivate
$ pip freeze

If you have not installed the requests package prior to this tutorial, you should not see it in the list of installed packages

What happened here is when you ran deactivate you are put back in the system's default Python Interpreter instead of the virtual environment's.

The requests package was installed in the virtual environment.


Thanks for taking the time to read! If you have any questions, comments, or concerns I would love to hear them!

Discussion (0)