如何将Python Virtual Environment Wrapper创建的虚拟环境存储到项目目录并关联对应项目?
Since you organize projects by domain (e.g., ML projects in /home/me/Projects/ml-projects/) and want virtual environments tied directly to their respective projects instead of a central .local folder, here are two straightforward, practical approaches:
Approach 1: Link an Existing Project to a Project-Directory Virtual Environment
Perfect if you already have project folders set up and want to add a virtual environment right inside them:
Navigate to your project directory:
cd /home/me/Projects/ml-projects/my-opencv-projectCreate a virtual environment directly in the project folder (we’ll use
.venvas a standard hidden folder to keep things clean):virtualenv .venvActivate the new virtual environment:
source .venv/bin/activateLink this virtual environment to your project directory using virtualenvwrapper:
setvirtualenvprojectThis command tells virtualenvwrapper that the active environment is tied to your current working directory. Now, whenever you run
workon my-opencv-project, you’ll automatically jump into your project folder with the environment activated.Test the setup:
Runworkon my-opencv-project— your terminal prompt will show the environment name, and you’ll be in the project directory immediately.
Approach 2: Configure mkproject to Create Environments Inside Project Folders
If you want new projects and their environments to live in your Projects structure by default, tweak your virtualenvwrapper config:
Open your
~/.bashrcfile and add these lines after your existing virtualenvwrapper setup:# Set your root projects directory export PROJECT_HOME=/home/me/Projects # Tell mkproject to create the virtual environment inside the project folder export VIRTUALENVWRAPPER_PROJECT_FILENAME=.venvReload your bashrc to apply changes:
source ~/.bashrcCreate a new project with linked environment:
Runmkproject ml-projects/new-opencv-project— this will:- Create the project directory at
/home/me/Projects/ml-projects/new-opencv-project - Generate the virtual environment inside that directory at
.venv - Automatically link the environment to the project, so
workon new-opencv-projecttakes you straight to the project folder.
- Create the project directory at
Quick Tips
- Add
.venv/to your project’s.gitignore(if using Git) to avoid accidentally committing environment files. - This setup makes project migration way easier — you can move the entire project folder, and the virtual environment goes right along with it.
内容的提问来源于stack exchange,提问作者joesan

