How to Create and Activate a Python Virtual Environment

Python virtual environment creates an isolated Python working environment that you could install python module dependencies without influence of global Python modules. It is essential especially your project has 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 two methods below. Your console changes to something like below

    (your_project)user@hostname:~/your_project$
    

    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
    user@hostname:~/your_project$