claude-code
claude-code copied to clipboard
Search for Python virtualenv in .venv/
I usually create a virtualenv as a dotfile/dotdir for Python projects, naming it .venv/, which is the standard convention for Pycharm projects. However, I’ve noticed that claude-code searches for virtualenv directories (ex. venv/) within the project directory but doesn’t automatically discover the hidden one.
As a result, it often requires manual prompting to source the virtual environment after each compact. To address this issue, I’ve added an instruction to CLAUDE.md to locate my virtual environment in that directory, but it seems to be largely ignored.
I believe this can be divided into two enhancements:
- Improve Python project virtualenv detection by checking for
.venv/during/initand other relevant times - If possible, enhance the ability to follow setup instructions from
CLAUDE.mdabout virtualenv more consistently or make it "sticky" (?)
I have the same issue. Claude uses the environment if the user asks, but it doesn't find instructions in CLAUDE.md, and doesn't remember through /compact.
Claude just doesn't care to execute commands in the local python environment. Always the same result
Bash(source .venv/bin/activate && python --version && python simple_test.py)… ⎿ Error: Python 3.12.10 Current directory: /System/Volumes/Data/idev/prj Installed packages: /System/Volumes/Data/idev/prj /System/Volumes/Data/idev/prj /opt/homebrew/Cellar/[email protected]/3.12.10/Frameworks/Python.framework/Versions/3.12/lib/python312.zip /opt/homebrew/Cellar/[email protected]/3.12.10/Frameworks/Python.framework/Versions/3.12/lib/python3.12 /opt/homebrew/Cellar/[email protected]/3.12.10/Frameworks/Python.framework/Versions/3.12/lib/python3.12/lib-dynload /opt/homebrew/lib/python3.12/site-packages Error importing cv2: No module named 'cv2'
Really crazy.
I had success by customizing the PATH variable in settings.local.json
I am also struggling with this. We should be able to set up commands that run in the context of Claude's shell like activating a virtual environment, so that Claude doesn't need to activate it itself. That's something that should be managed in code, not by asking the AI to do it, both to save on tokens and improve consistency.
The True "Best" Solution: Environment Virtualization
The best and most reliable solution isn't to help the agent find the right environment. It's to force the agent to start in the correct environment from the beginning.
Solution: Use Dev Containers (Docker)
This method completely sidesteps the problem of environment detection because the agent's terminal is already configured correctly the moment it starts.
- How it works: You define your entire development setup in a
Dockerfileand adevcontainer.jsonfile. This includes the right Python version, the activated virtual environment, and all your project's dependencies. When the agent starts a session, it runs inside this pre-built container. The shell'sPATHis already correct,pythonis already pointing to the venv's interpreter, and every tool is installed and ready to go. - Why it's the gold standard for all agents:
- Explicit & Unambiguous: There's no guesswork. The agent doesn't need to detect anything or remember to activate a script because it's already active.
- Reproducible: It guarantees the environment is exactly the same for you, the agent, and anyone else on your team.
- Portable: This works across the board with VS Code Dev Containers, GitHub Codespaces, or any other tool that can use a Docker container. A smart enough agent can even be told to use Docker directly.
This is the industry-standard way to manage complex environments, and it solves the root of this AI interaction problem.
The Most Practical Immediate Fix
If you can't set up a Dev Container, the next best thing is to directly control how the agent's shell finds its tools.
Solution: PATH Customization
This is the most effective workaround because it changes how the agent's shell fundamentally finds programs.
- How it works: You add your virtual environment's
bindirectory to the very beginning of thePATHvariable. This ensures that whenever the agent runs a command likepythonorpip, the shell finds the version in your.venvbefore it finds the system's global version. - Example for
settings.local.jsonor a similar config file:{ "terminal.integrated.env.linux": { "PATH": "${workspaceFolder}/.venv/bin:${env:PATH}" } } - Why it's better than prompting:
- Persistent for the session: This fixes the environment for the agent's entire session, so you don't have to keep reminding it to activate the venv.
- Harder for the AI to "forget": You're giving a direct command to the shell itself, which is far more reliable than a natural language prompt that the AI can forget or ignore after a few commands.
Hierarchy of Solutions (from Best to Worst)
Here’s a ranking of solutions that should apply to any coding agent.
| Rank | Solution | Pros | Cons | Best For |
|---|---|---|---|---|
| 1 | Dev Containers (Docker) | Basically foolproof. It's 100% reproducible and works for everyone, human or AI. Solves the actual problem instead of patching it. | Has an initial setup cost. Requires Docker to be installed. | Serious projects, teams, and anyone who wants a solution that just works. |
| 2 | PATH Customization | Very reliable. A "set it and forget it" fix for the session that directly tells the shell what to do. | Needs a config file that the agent will actually use, like settings.json or .bashrc. |
The best practical fix for anyone who doesn't want to deal with Docker. |
| 3 | Clear Initial Instructions | Simple and fast. It correctly sets the agent's context for its first few actions. | Not reliable. Agents often forget initial instructions during long or complex tasks due to context window limits. | A good thing to do with other solutions, but it isn't a solution by itself. |
| 4 | Manual Prompting (Re-activating) | Dead simple, with no setup needed. | Incredibly annoying and easy to mess up. You have to constantly babysit the agent and it breaks your flow. | The last resort when nothing else is working. |
| 5 | Relying on CLAUDE.md |
Good for documenting the project for humans and maybe for the AI to see. | Agents are known to ignore these files. The AI's programming doesn't consistently treat them as a required set of instructions. | Documenting your project, not reliably controlling an agent. |
The Ideal Future State (What AI Providers Should Build)
Ultimately, the ball is in the AI providers' court to fix this permanently.
- Automatic Workspace Scanning: When an agent starts (
/init), it should be smart enough to scan for common project files (pyproject.toml,requirements.txt,Pipfile) and environment folders like.venvorvenv. - Stateful Environment Activation: When it finds a virtual environment, it should activate it automatically and then stay in that environment for the whole session. This means it should internally add
./.venv/binto itsPATHfor all commands it runs. - Prioritizing Configuration Files: The agent's model needs to be tuned to give top priority to instructions in config files like
CLAUDE.mdor.ai-instructions.md. It should treat them like system-level rules that override its default behavior.
tldr; For now, stop trying to make the agent remember things. Instead, create an environment where it doesn't have a choice. Use Dev Containers for a bulletproof solution, or use PATH customization for the most practical and effective workaround.
I found the solution, just activate the .venv first, then run claude. It will inherit the env. Silly, but works ~
Copying in the issue that I opened just to consolidate disussion around this here. The point above is interesting!
Preflight Checklist
- [x] I have searched existing requests and this feature hasn't been requested yet
- [x] This is a single feature request (not multiple features)
Problem Statement
When working with Python code generation tools (e.g., Claude, GPT, etc.), a recurring frustration is their tendency to default to system Python rather than using a virtual environment (venv).
Even when workspace instructions explicitly request the use of a virtual environment (for example, by including a rule in Claude.md to always create and use a venv via UV), the agent often ignores these directions and installs packages into the system Python.
Additionally, when a virtual environment is used, the agent frequently reactivates it before every shell command, rather than maintaining a persistent session. This is inefficient and unrepresentative of real developer workflows.
Proposed Solution
Implement intelligent virtual environment management that mimics human developer behavior.
-
Automatic Detection and Activation
- Detect an existing virtual environment by checking for standard folders like
.venv/,venv/, or.env/. - Automatically activate the detected environment instead of creating a new one unnecessarily.
- Detect an existing virtual environment by checking for standard folders like
-
Intelligent Creation
- If no environment exists, create one using the specified package manager (e.g.,
uv venvorpython -m venv) before installing dependencies.
- If no environment exists, create one using the specified package manager (e.g.,
-
Session-Persistent Activation
- Activate the venv once and persist the environment for the session.
- All subsequent commands should execute within that activated environment, without repeated activation calls.
-
Configurable Defaults
- Support configuration through workspace files (e.g.,
.claude.mdor YAML-based workspace configs):python: use_virtual_env: true manager: uv detect_existing_env: true persistent_activation: true
- Support configuration through workspace files (e.g.,
Alternative Solutions
No response
Priority
Medium - Would be very helpful
Feature Category
CLI commands and flags
Use Case Example
No response
Additional Context
No response
Reactivating every time is perfectly fine. If you want it to be persistent, activate it before running claude.
Newer Claude models are already better at reading instructions than Sonnet 3.5 when this issue was first created