"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Python Environment Setup

Python Environment Setup

Published on 2024-10-31
Browse:140

Python Environment Setup

I am a python developer and usually work with multiple repositories at any time. Most of these projects have different dependencies so I create a virtual environment in every project. I prefer creating virtual env right next to code. Pycharm also detects it when repository is opened in Pycharm.

This setup worked most of the time but sometimes, I activate venv of one repository and then change it another repository without changing activating correct environment. I usually spotted this when code execution used to fail and never lost more than a minute on this but, this always made me think what if there is a shell that could run something when you enter a directory?

I decided to implement something simple in shell script temporarily. I ended up with creating small function, aliased with cd and added in my .bashrc.

It's a simple function and all I ever needed. It does,

  1. Loads the .venv from that repository
  2. Additionally, sources .cdenv, i usually set env variable but you can do anything in there.

I was okay with not deactivating/resetting environment when i exited the directory.

Add below function in .bashrc and you should be able to use it.

Note: If you create your virtual environment with different name then please change the name in code below.

function cd() {
  # Run a shell `cd` command or error
  command cd "$@" || return

  # If .venv exists in the directory
  if [[ -d .venv ]]; then
    # Deactivate any initialized virtual env, ignore error
    deactivate > /dev/null 2>&1

    # activate .venv
    source .venv/bin/activate
    echo "deactivate prev venv and activate current venv"
  fi

  # Load a .cdenv file
  if [[ -f .cdenv ]]; then
      echo "loading .cdenv"
      source ./.cdenv
  fi
}
Release Statement This article is reproduced at: https://dev.to/ninadmhatre/python-environment-setup-i3b?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3