Python virtualenv

As we all know python is a multi purpose programmng language, and their applications goes from simple automation scripts for renaming your files, creating desktop apps, mobile apps, web apps, to use cutting edge packages designed for machine learning and data science, so how to manage all of these packages in a single machine avoiding the hassle of package confilcts and debendancies issues.

Introduction, motivation and Answering your Questions:

  1. Why we need Virtual environments

  2. Why to use virtualenv instead of any other tool ?

  3. Why we need Virtual environments

  4. Why to use virtualenv instead of any other tool ?


How do I manage virtual environments in python?

Installing virtualenv:

  • $ python -m pip install --user virtualenv

  • Append virtualenv path to the bin path you will find it under /usr/.local/bin:

    1. Restart your terminal session
    2. find the absolute path for virtualenv: $ which virtualenv
    3. In my case it’s in $ /home/shrbo/.local/bin/virtualenv
    4. $ export PATH=/home/shrbo/.local/bin:$PATH
    5. Showing your path content $ echo $PATH make sure virtualenv path appear

The file hierarchical for managing different environments:

The below dir hierarchical which I use for managing different envs in the same machine

python-working
|
|__ venvs
|   |
|   |__ flask
|   |
|   |__ tensorflow-gpu
|   |
|   |__ webdev
|
|__ projects
    |
    |__ tech-blog
    |
    |__ stacked-autoencoders

So what is going on here: creating two folders one for venvs and the other for projects, under venvs folder I can go and create any enviroment, then I go and activte that environment go back to the project that I want and get work done.


Lab creating an environment for a blog:

  • Creating your dirs mkdir venvs && cd venvs

  • $ virtualenv --python=$(which python3) webdev

    • --python= specifing the full python version path
    • webdev the name of the environment
  • Activate the venv Bash shell $ source webdev/bin/activate

  • Activate the venv Fish shell $ . webdev/bin/activate.fish

  • install required libs using pip $ pip3 install flask

  • Start working on your project $ cd ../projects && mkdir new-blog

  • To deactivate the venv $ deactivate

  • removing venv $ rm -rf webdev


Integrate your virtualenvs with vscode:

So as we see above we have a folder for virtualenv and I use vscode

  1. First go to vscode and hit ctrl + , to open the settings
  2. Choose the user settings tab and type in the search python venv
  3. Type the absolute path for the venvs folder in the /home/shrbo/python_working/venvs
  4. Restart vscode
  5. Hit ctrl + shift + p and type python: select interpreter then hit return
  6. Choose the virtualenv that you want an hit return πŸ‘ πŸ‘