Create and Activate a Python Virtual Environment

Python virtual environment creates an isolated Python working environment that you could install python module dependencies without the influence of global Python modules. It is essential especially if your project has a different Python library version requirement so that you could install the specific library version only in that virtual environment.

You could follow the steps below to install, create, activate and also deactivate the Python virtual environment.

  • Install virtualenv

    In some distribution, virtualenv is already installed. You could check whether your distribution has already included it by

    $ virtual --version

    If not, install virtualenv via pip

    $ pip install virtualenv

    or via apt-get

    $ apt-get install python-virtualenv
  • Create Project Virtual Environment

    Use virtualenv to create the project Python virtual environment

    $ cd your_project_folder
    $ virtualenv your_project
  • Activate Project Virtual Environment
    $ source your_project/bin/activate

    It activates your project virtual environment. You could verify it by either of the two methods below. Your console changes to something like below

    How to manage Python projects using...
    How to manage Python projects using Virtualenv

    Or list the system PATH environment variable

    $ echo $PATH

    You should see your_project path in the printed information.

  • Deactivate virtualenv

    If you want to switch to another virtual environment or simply quit the current virtual environment, you could deactivate your virtualenv by

    (your_project)user@hostname:~/your_project$ deactivate

Related Article - Python virtualenv

  • Virtualenv in Python3