Python Virtualenv

Posted by The Sauce Labs Team in Software Development & Testing

Python logo iconA Python virtualenv is a Python interpreter and set of installed Python packages. Python packages are installed separate from the main system so you don't need to use sudo/su or worry about installing things system-wide. Since the interpreter (the python run) and packages in a virtualenv are separate from other virtualenvs, you can switch between different versions of Python and different versions of installed packages with a single command. Using virtualenv lets you do things like:

  • Replicate your production Python environment in a dev setup so you can be sure you're writing code and tests using the same package versions your deployed code will use.
  • Create environments with the same set of Python packages but using different versions of the Python interpreter (e.g., Python 2.5, Python 2.7, and PyPy).
  • Setup experimental environments for trying out new Python package versions or new Python software projects.

The easiest way to get going with virtualenv on Mac and Linux is to use the virtualenv-burrito installer. This one-line command installs virtualenv and virtualenvwrapper (a nice way to use virtualenvs):

curl -s | $SHELL

Once installed, you can make new virtualenvs with mkvirtualenv <name>, install packages with pip install <package>, and switch between virtualenvs using workon <name>. Let's make a virtualenv and run the example Sauce Labs test:

mkvirtualenv saucelabs
pip install selenium

Login to (or create a free account on) Go to the Python getting started page, copy your private curl command, and run it like:

curl -s | bash

To install the same Python package versions in another virtualenv we can use pip freeze to get what's in our current environment, save it to a file, and use that file as an install list:

workon saucelabs
pip freeze > requirements.txt
mkvirtualenv likesaucelabs
pip install -r requirements.txt

By developing, testing, and running production Python code in virtualenvs created using the same requirements files, you greatly reduce the risk of writing bugs which only show up in one environment but not another. We highly recommend using this tool to help ship code faster.

Discuss: Python Virtualenv

Free Trial

Get access to a free 14-day trial version, or contact Sales for more information.