What non-python devs need to know about virtualenv

Sergio Fraile
2 min readSep 30, 2019

--

The truth is that devs are often required to go to python for some reason or another. In my case, I only use python for machine learning; but it is not my primary language and it did required a bit of time to catch up with it. In hopes to easy that pain for other devs, this are my needed commands for working with virtualenv.

For those that don’t know what virtualenv is, you can check the documentation here, but in a nutshell, it is a tool to create an isolated environment for working with python, so whatever we install or do there, doesn’t affect our global python installation.

Installation

There are several ways you may install virtualenv depending on your system (apt-get, brew, etc), but for most cases, you may actually want to install it in your global python installation:

> pip install virtualenv

Usage

Once you have virutalenv installed, you can create a new virutal environment (venv) as follows (don’t forget to browse to your project folder first, as the command will be executed in your current directory):

> virtualenv -p python3 venv

Then you activate your virtual environment as follows:

> source venv/bin/activate

For running python files within your virtual environment from shell, you will have to call it from your venv python location:

> venv/bin/python my_python_script.py

Gathering dependencies

Of course since you have your venv, whatever you need to install (Tensorflow, numpy, pandas, etc) will be installed within this environment via pip.

One of the things you can do with pip, that works pretty well for venv, is to output your dependencies in a .txt file and import them, so you can easily share your environment configuration.

For saving your dependencies, you can use:

> env1/bin/pip freeze > requirements.txt

And you can install the dependencies from a .txt list as follows:

> env2/bin/pip install -r requirements.txt

I hope that you have find this little snippets useful. I really encourage you to use virutalenv whenever is possible.

And please don’t hesitate to let feedback or improvements in the comments!

--

--

Sergio Fraile

Mobile developer 📱 @ Workday | All things mobile (iOS, Android and Flutter) + ML | GDG Cloud Dublin organizer