How to Create and Activate a Python Virtual Environment

Jinku Hu Feb 02, 2024
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 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


    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
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - Python virtualenv