Python Environment Setup

WBOY
Release: 2024-08-13 06:54:12
Original
318 people have browsed it

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 }
Copy after login

The above is the detailed content of Python Environment Setup. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!