DEV Community

Ninad Mhatre
Ninad Mhatre

Posted on

4 1 1 1 1

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
}
Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (1)

Collapse
 
martinbaun profile image
Martin Baun

PyCharm as your IDE is the bomb. Out of the box, creating a new project will create and enable a virtual environment for you. From there you just 'pip install' using the PyCharm terminal like you would anyway.
Thanks for putting that in detail!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs