managing-environments

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Managing Development Environments

开发环境管理

Guidelines for working with Python virtual environments (venv) and conda environments. This skill ensures safe, organized package installations by always checking and confirming the active environment before proceeding.
本文档是Python虚拟环境(venv)和conda环境的使用指南。通过在操作前始终检查并确认当前激活的环境,可确保包安装过程安全、有序。

When to Use This Skill

何时使用本技能

Activate this skill whenever:
  • Installing Python packages or tools
  • User requests to install dependencies
  • Setting up a new Python project
  • Debugging import or package issues
  • Working with any Python development
在以下场景中启用本技能:
  • 安装Python包或工具时
  • 用户请求安装依赖时
  • 搭建新Python项目时
  • 调试导入或包相关问题时
  • 进行任何Python开发工作时

Core Principles

核心原则

  1. Always check environment status before any installation
  2. Always confirm with user which environment to use
  3. Never install without environment confirmation
  4. Warn if no environment is active
  5. Help user choose appropriate environment type

  1. 安装前务必检查环境状态
  2. 务必与用户确认要使用的环境
  3. 未确认环境时绝不要进行安装
  4. 如果没有激活的环境,发出警告
  5. 帮助用户选择合适的环境类型

Environment Detection Workflow

环境检测流程

Step 1: Check Environment Status

步骤1:检查环境状态

Before ANY installation command, run these checks:
bash
undefined
在执行任何安装命令之前,运行以下检查:
bash
undefined

Check for active venv

检查是否激活venv

echo "Python executable: $(which python)" echo "Virtual environment: $VIRTUAL_ENV"
echo "Python可执行文件路径: $(which python)" echo "虚拟环境: $VIRTUAL_ENV"

Check for conda environment

检查conda环境

echo "Conda environment: $CONDA_DEFAULT_ENV" conda info --envs 2>/dev/null || echo "Conda not available"
undefined
echo "Conda环境: $CONDA_DEFAULT_ENV" conda info --envs 2>/dev/null || echo "Conda未安装"
undefined

Step 2: Interpret Results

步骤2:解读检测结果

Scenario A: venv is active
Python executable: /path/to/project/.venv/bin/python
Virtual environment: /path/to/project/.venv
Conda environment:
→ Python venv is active
Scenario B: conda environment is active
Python executable: /path/to/miniconda3/envs/myenv/bin/python
Virtual environment:
Conda environment: myenv
→ Conda environment is active
Scenario C: No environment (system Python)
Python executable: /usr/bin/python
Virtual environment:
Conda environment:
→ ⚠️ No environment active! Warn user.
Scenario D: Both detected (rare)
Virtual environment: /path/to/.venv
Conda environment: base
→ Both active, prioritize what
which python
shows, but confirm with user
场景A:venv已激活
Python可执行文件路径: /path/to/project/.venv/bin/python
虚拟环境: /path/to/project/.venv
Conda环境:
→ Python venv已激活
场景B:conda环境已激活
Python可执行文件路径: /path/to/miniconda3/envs/myenv/bin/python
虚拟环境:
Conda环境: myenv
→ Conda环境已激活
场景C:无激活环境(系统Python)
Python可执行文件路径: /usr/bin/python
虚拟环境:
Conda环境:
→ ⚠️ 未检测到激活的环境!向用户发出警告。
场景D:同时检测到两种环境(罕见)
虚拟环境: /path/to/.venv
Conda环境: base
→ 两种环境均已激活,优先以
which python
的结果为准,但需与用户确认。

Step 3: Confirm with User

步骤3:与用户确认

Always ask before proceeding:
I've detected the following environment:
- Environment type: [venv/conda/none]
- Location: [path]
- Python version: [version]

Is this the environment you want me to use for installing [package/tool]?
Wait for user confirmation before proceeding.

操作前务必询问用户:
我检测到以下环境:
- 环境类型:[venv/conda/无]
- 位置:[路径]
- Python版本:[版本]

是否要使用此环境安装[包/工具]?
等待用户确认后再继续操作。

Installation Patterns by Environment Type

按环境类型分类的安装模式

For Python venv

Python venv环境

bash
undefined
bash
undefined

Activate (if needed)

激活环境(如需要)

source .venv/bin/activate # Linux/Mac
source .venv/bin/activate # Linux/Mac

or

.venv\Scripts\activate # Windows
.venv\Scripts\activate # Windows

Install packages

安装包

pip install package-name
pip install package-name

Install with specific version

安装指定版本

pip install package-name==1.2.3
pip install package-name==1.2.3

Install from requirements

从requirements文件安装

pip install -r requirements.txt
pip install -r requirements.txt

Install development dependencies

安装开发依赖

pip install -e ".[dev]"
undefined
pip install -e ".[dev]"
undefined

For Conda Environment

Conda环境

bash
undefined
bash
undefined

Activate (if needed)

激活环境(如需要)

conda activate environment-name
conda activate environment-name

Install from conda-forge (preferred for scientific packages)

从conda-forge安装(科学计算包优先选择)

conda install -c conda-forge package-name
conda install -c conda-forge package-name

Install with pip (if not available in conda)

若conda源中无此包,使用pip安装

pip install package-name
pip install package-name

Install from environment file

从环境文件安装

conda env update -f environment.yml
conda env update -f environment.yml

Install specific version

安装指定版本

conda install package-name=1.2.3
undefined
conda install package-name=1.2.3
undefined

Critical: Channel Priority for Conda

关键:Conda频道优先级

For bioinformatics/scientific packages:
  1. Try
    conda-forge
    first:
    conda install -c conda-forge package
  2. Try
    bioconda
    for bio tools:
    conda install -c bioconda package
  3. Fall back to pip only if not available:
    pip install package
Why: Conda manages binary dependencies better than pip for scientific packages.
对于生物信息学/科学计算包:
  1. 优先尝试
    conda-forge
    conda install -c conda-forge package
  2. 生物工具尝试
    bioconda
    conda install -c bioconda package
  3. 仅当以上均无此包时,再使用pip:
    pip install package
原因:对于科学计算包,Conda比pip更擅长管理二进制依赖。

Handling Conda TOS Acceptance Errors

处理Conda服务条款接受错误

If conda installation fails with:
CondaToSNonInteractiveError: Terms of Service have not been accepted
Solution: Use pip instead (installed packages work identically):
bash
/path/to/envs/ENV_NAME/bin/pip install PACKAGE_NAME
Example - Installing JupyterLab:
bash
undefined
如果conda安装时出现以下错误:
CondaToSNonInteractiveError: Terms of Service have not been accepted
解决方案:改用pip安装(安装的包与conda安装的功能完全一致):
bash
/path/to/envs/ENV_NAME/bin/pip install PACKAGE_NAME
示例 - 安装JupyterLab:
bash
undefined

This fails with TOS error

此命令会因服务条款错误失败

conda install -n curation_paper -c conda-forge jupyterlab -y
conda install -n curation_paper -c conda-forge jupyterlab -y

Use pip instead

改用pip安装

/Users/delphine/miniconda3/envs/curation_paper/bin/pip install jupyterlab

Packages installed via pip integrate seamlessly with conda environments.

---
/Users/delphine/miniconda3/envs/curation_paper/bin/pip install jupyterlab

通过pip安装的包可与conda环境无缝集成。

---

No Environment Active - Warning & Planning

未检测到激活环境 - 警告与规划

If no environment is detected, DO NOT PROCEED with installation. Instead:
如果未检测到任何环境,请勿继续安装。请按以下步骤操作:

Step 1: Warn User

步骤1:向用户发出警告

⚠️ WARNING: No Python environment detected!

You're currently using system Python:
- Location: [path to python]
- Version: [version]

Installing packages to system Python can:
- Cause conflicts with system packages
- Require sudo/admin privileges
- Make projects difficult to reproduce
- Break system tools that depend on specific versions

I recommend creating a virtual environment first.
⚠️ 警告:未检测到Python环境!

您当前正在使用系统Python:
- 位置:[Python路径]
- 版本:[版本]

向系统Python安装包可能会:
- 与系统包产生冲突
- 需要sudo/管理员权限
- 导致项目难以复现
- 破坏依赖特定版本的系统工具

我建议您先创建一个虚拟环境。

Step 2: Help Choose Environment Type

步骤2:帮助用户选择环境类型

Ask user about their project needs:
Decision Tree:
Question: What type of project are you working on?

A. Pure Python project (web dev, scripting, etc.)
   → Recommend: Python venv
   → Fast, lightweight, standard Python tool

B. Data science / Scientific computing
   → Ask: Do you need non-Python dependencies? (R, C libraries, etc.)

   B1. Yes (or using packages like numpy, scipy, pandas, etc.)
       → Recommend: Conda
       → Better binary dependency management

   B2. No, only Python packages
       → Recommend: Python venv
       → Simpler and faster

C. Bioinformatics / Genomics
   → Recommend: Conda (with bioconda channel)
   → Most tools available via bioconda
   → Manages complex dependencies well

D. Galaxy tool development
   → Recommend: Conda
   → Galaxy uses conda for tool dependencies
   → Direct compatibility
询问用户的项目需求:
决策树:
问题:您正在开发什么类型的项目?

A. 纯Python项目(Web开发、脚本等)
   → 推荐:Python venv
   → 快速、轻量,是Python标准工具

B. 数据科学/科学计算
   → 追问:您是否需要非Python依赖?(如R、C库等)

   B1. 是(或使用numpy、scipy、pandas等包)
       → 推荐:Conda
       → 更擅长管理二进制依赖

   B2. 否,仅使用Python包
       → 推荐:Python venv
       → 更简单、快速

C. 生物信息学/基因组学
   → 推荐:Conda(搭配bioconda频道)
   → 多数工具可通过bioconda获取
   → 能很好地管理复杂依赖

D. Galaxy工具开发
   → 推荐:Conda
   → Galaxy使用conda管理工具依赖
   → 直接兼容

Step 3: Offer to Create Environment

步骤3:协助创建环境

For venv:
bash
undefined
创建venv环境:
bash
undefined

Create venv

创建venv

python -m venv .venv
python -m venv .venv

Activate

激活环境

source .venv/bin/activate # Linux/Mac
source .venv/bin/activate # Linux/Mac

Verify

验证

which python

**For conda:**
```bash
which python

**创建Conda环境:**
```bash

Create conda environment

创建conda环境

conda create -n project-name python=3.11
conda create -n project-name python=3.11

Activate

激活环境

conda activate project-name
conda activate project-name

Verify

验证

conda info --envs which python

---
conda info --envs which python

---

Common Scenarios

常见场景

Scenario 1: User Asks to Install Package

场景1:用户请求安装包

❌ Bad (without checking):
pip install pandas
✅ Good (with environment check):
1. Check environment status
2. Show user what environment is active
3. Ask: "Is this the environment you want to use?"
4. Wait for confirmation
5. Then: pip install pandas (or conda install as appropriate)
❌ 错误做法(未检查环境):
pip install pandas
✅ 正确做法(先检查环境):
1. 检查环境状态
2. 告知用户当前激活的环境
3. 询问:"是否要使用此环境进行安装?"
4. 等待用户确认
5. 执行:pip install pandas(或根据环境选择conda install)

Scenario 2: Multiple Packages Needed

场景2:需要安装多个包

User: "Install pandas, numpy, and matplotlib"
Response:
Let me first check your environment...

[run environment detection]

I've detected: [environment details]

I need to install:
- pandas
- numpy
- matplotlib

Is this the correct environment? Should I use [pip/conda install -c conda-forge]?
用户: "安装pandas、numpy和matplotlib"
回复:
我先检查一下您的环境...

[执行环境检测]

我检测到:[环境详情]

需要安装的包:
- pandas
- numpy
- matplotlib

是否使用此环境?是否采用[pip/conda install -c conda-forge]进行安装?

Scenario 3: User in Wrong Environment

场景3:用户处于错误环境

User: "Install scikit-learn" (but they're in a different project's venv)
Response:
⚠️ I've detected you're in a virtual environment at:
/path/to/other-project/.venv

But we're working in directory:
/path/to/current-project

This might be the wrong environment. Options:
1. Deactivate and create/activate the correct environment for this project
2. Continue with current environment (if this is intentional)
3. Cancel installation

Which would you prefer?
用户: "安装scikit-learn"(但用户处于另一个项目的venv环境中)
回复:
⚠️ 我检测到您当前处于以下虚拟环境:
/path/to/other-project/.venv

但我们当前的工作目录是:
/path/to/current-project

这可能是错误的环境。可选操作:
1. 退出当前环境,创建/激活当前项目的正确环境
2. 继续使用当前环境(如果是有意为之)
3. 取消安装

您希望我执行哪项操作?

Scenario 4: Conda Base Environment

场景4:用户处于Conda base环境

Detection: User is in conda base environment
Response:
⚠️ You're currently in the conda 'base' environment.

It's generally better practice to create a separate environment for each project
to avoid dependency conflicts.

Options:
1. Create a new conda environment for this project
2. Continue with base environment (not recommended)

Would you like me to create a project-specific environment?

检测结果: 用户处于conda base环境
回复:
⚠️ 您当前处于conda的base环境中。

通常建议为每个项目创建独立的环境,以避免依赖冲突。

可选操作:
1. 为此项目创建新的conda环境
2. 继续使用base环境(不推荐)

是否需要我为您创建项目专属环境?

Environment Selection Guidelines

环境选择指南

Use Python venv When:

优先选择Python venv的场景:

  • ✅ Pure Python project
  • ✅ Simple dependencies (all available on PyPI)
  • ✅ Standard web development (Django, Flask, FastAPI)
  • ✅ No compiled extensions or C libraries
  • ✅ Want fastest environment creation
  • ✅ Working with Python 3.3+
Advantages:
  • Lightweight and fast
  • Built into Python (no extra installation)
  • Simple and standard
  • Works on all platforms
Disadvantages:
  • Harder to manage non-Python dependencies
  • Binary packages may need system libraries
  • Version conflicts harder to resolve
  • ✅ 纯Python项目
  • ✅ 依赖简单(所有包均可在PyPI获取)
  • ✅ 标准Web开发(Django、Flask、FastAPI)
  • ✅ 无需编译扩展或C库
  • ✅ 希望快速创建环境
  • ✅ 使用Python 3.3及以上版本
优势:
  • 轻量、快速
  • 内置在Python中(无需额外安装)
  • 简单、标准
  • 跨平台兼容
劣势:
  • 难以管理非Python依赖
  • 二进制包可能需要系统库支持
  • 版本冲突更难解决

Use Conda Environment When:

优先选择Conda环境的场景:

  • ✅ Data science / machine learning
  • ✅ Scientific computing (numpy, scipy, pandas)
  • ✅ Bioinformatics / genomics
  • ✅ Need specific Python versions
  • ✅ Cross-language dependencies (R, C++, etc.)
  • ✅ Galaxy tool development
  • ✅ Complex binary dependencies
Advantages:
  • Manages binary dependencies
  • Cross-language support
  • Better for scientific packages
  • Can manage Python version
  • Excellent for reproducibility
Disadvantages:
  • Slower than venv
  • Larger disk space usage
  • Requires conda installation
  • More complex

  • ✅ 数据科学/机器学习
  • ✅ 科学计算(numpy、scipy、pandas)
  • ✅ 生物信息学/基因组学
  • ✅ 需要特定Python版本
  • ✅ 跨语言依赖(R、C++等)
  • ✅ Galaxy工具开发
  • ✅ 复杂二进制依赖
优势:
  • 可管理二进制依赖
  • 支持跨语言
  • 更适合科学计算包
  • 可管理Python版本
  • 可复现性强
劣势:
  • 比venv慢
  • 占用更多磁盘空间
  • 需要安装Conda
  • 操作更复杂

Best Practices

最佳实践

1. One Environment Per Project

1. 每个项目对应一个独立环境

Good:
project-a/
├── .venv/          # project-a's environment
├── requirements.txt
└── src/

project-b/
├── .venv/          # project-b's environment
├── requirements.txt
└── src/
Bad:
undefined
正确示例:
project-a/
├── .venv/          # project-a专属环境
├── requirements.txt
└── src/

project-b/
├── .venv/          # project-b专属环境
├── requirements.txt
└── src/
错误示例:
undefined

Using same environment for multiple projects

多个项目共用同一个环境

→ Version conflicts inevitable

→ 必然会出现版本冲突

undefined
undefined

2. Document Environment Setup

2. 文档化环境搭建流程

Always create environment specification files:
For venv:
bash
undefined
务必创建环境规格文件:
venv环境:
bash
undefined

Create requirements.txt

创建requirements.txt

pip freeze > requirements.txt
pip freeze > requirements.txt

Or for development

或创建开发环境依赖文件

pip freeze > requirements-dev.txt

**For conda:**
```bash
pip freeze > requirements-dev.txt

**Conda环境:**
```bash

Create environment.yml

创建environment.yml

conda env export > environment.yml
conda env export > environment.yml

Or minimal version

或创建精简版环境文件

conda env export --from-history > environment.yml
undefined
conda env export --from-history > environment.yml
undefined

3. Add Environment to .gitignore

3. 将环境目录添加到.gitignore

gitignore
undefined
gitignore
undefined

Python venv

Python venv

.venv/ venv/ env/
.venv/ venv/ env/

Conda

Conda

.conda/
undefined
.conda/
undefined

4. Include Python Version

4. 明确Python版本

For venv (in README):
Python 3.11+ required
For conda (in environment.yml):
yaml
name: myproject
dependencies:
  - python=3.11
  - pandas
  - numpy

venv环境(在README中说明):
需要Python 3.11及以上版本
Conda环境(在environment.yml中指定):
yaml
name: myproject
dependencies:
  - python=3.11
  - pandas
  - numpy

Resumable Data Fetch Scripts

可恢复的数据获取脚本

Pattern for Long-Running Data Retrieval

长时数据获取脚本模式

When building scripts that fetch data from external sources (APIs, S3, etc.), implement these patterns for robustness:
python
def fetch_with_caching(item_id, output_dir):
    """Fetch data with local caching to support resume."""
    output_file = output_dir / f"{item_id}_data.txt"

    # Skip if already downloaded
    if output_file.exists():
        with open(output_file, 'r') as f:
            content = f.read()
        return True, "cached", content

    # Fetch logic here...
    # Save to file on success

    return success, status, content

def main():
    # Load existing results to skip completed work
    existing_csv = base_dir / 'results.csv'
    if existing_csv.exists():
        df_existing = pd.read_csv(existing_csv)
        existing_ids = set(df_existing['id'].tolist())
        df_to_process = df_to_process[~df_to_process['id'].isin(existing_ids)]
        print(f"Skipping {len(existing_ids)} items with existing data")

    # Process remaining items
    for item in df_to_process:
        success, status, data = fetch_with_caching(item, output_dir)
        # Process and accumulate results...

    # Merge with existing results
    if existing_csv.exists():
        df_existing = pd.read_csv(existing_csv)
        df_combined = pd.concat([df_existing, df_new], ignore_index=True)
    else:
        df_combined = df_new

    # Save combined results
    df_combined.to_csv(output_csv, index=False)
当构建从外部源(API、S3等)获取数据的脚本时,可实现以下模式以提升鲁棒性:
python
def fetch_with_caching(item_id, output_dir):
    """带本地缓存的数据获取函数,支持断点续传。"""
    output_file = output_dir / f"{item_id}_data.txt"

    # 若已下载则跳过
    if output_file.exists():
        with open(output_file, 'r') as f:
            content = f.read()
        return True, "cached", content

    # 此处编写数据获取逻辑...
    # 成功获取后保存到文件

    return success, status, content

def main():
    # 加载已有的结果以跳过已处理项
    existing_csv = base_dir / 'results.csv'
    if existing_csv.exists():
        df_existing = pd.read_csv(existing_csv)
        existing_ids = set(df_existing['id'].tolist())
        df_to_process = df_to_process[~df_to_process['id'].isin(existing_ids)]
        print(f"跳过{len(existing_ids)}个已处理项")

    # 处理剩余项
    for item in df_to_process:
        success, status, data = fetch_with_caching(item, output_dir)
        # 处理并累积结果...

    # 合并新结果与已有结果
    if existing_csv.exists():
        df_existing = pd.read_csv(existing_csv)
        df_combined = pd.concat([df_existing, df_new], ignore_index=True)
    else:
        df_combined = df_new

    # 保存合并后的结果
    df_combined.to_csv(output_csv, index=False)

Key Features

核心特性

  1. File-level caching: Save each fetch result immediately
  2. Resume capability: Skip already-processed items automatically
  3. Incremental results: Merge new results with existing data
  4. Interruption-safe: Can be stopped and restarted without data loss
  1. 文件级缓存:立即保存每个获取的结果
  2. 断点续传:自动跳过已处理项
  3. 增量结果:将新结果与已有数据合并
  4. 中断安全:可随时停止并重启,不会丢失数据

Progress Tracking

进度跟踪

python
try:
    from tqdm import tqdm
    iterator = tqdm(items, total=len(items), desc="Processing")
except ImportError:
    print("(Install tqdm for progress bar: pip install tqdm)")
    iterator = items
python
try:
    from tqdm import tqdm
    iterator = tqdm(items, total=len(items), desc="处理中")
except ImportError:
    print("(安装tqdm以显示进度条:pip install tqdm)")
    iterator = items

Rate Limiting

请求频率限制

python
import time

for item in items:
    result = fetch_data(item)
    if result.success:
        time.sleep(0.2)  # Be respectful to external services
This pattern makes scripts production-ready and user-friendly for long-running operations.

python
import time

for item in items:
    result = fetch_data(item)
    if result.success:
        time.sleep(0.2)  # 尊重外部服务,避免请求过于频繁
此模式可让脚本具备生产环境可用性,且在长时运行时更友好。

Troubleshooting

故障排除

Issue 1: "pip: command not found" in venv

问题1:venv中出现"pip: command not found"

Problem: venv created but pip not available
Solution:
bash
python -m ensurepip
python -m pip install --upgrade pip
问题描述:已创建venv但无法使用pip
解决方案
bash
python -m ensurepip
python -m pip install --upgrade pip

Issue 2: Conda environment activation fails

问题2:Conda环境激活失败

Problem:
conda activate
doesn't work
Solution:
bash
undefined
问题描述
conda activate
命令无效
解决方案
bash
undefined

Initialize conda for shell

为当前shell初始化conda

conda init bash # or zsh, fish, etc.
conda init bash # 或zsh、fish等

Restart shell or source

重启shell或重新加载配置

source ~/.bashrc
undefined
source ~/.bashrc
undefined

Issue 3: Wrong Python version in environment

问题3:环境中的Python版本不符合预期

For venv:
bash
undefined
venv环境解决方案
bash
undefined

Specify Python version when creating

创建环境时指定Python版本

python3.11 -m venv .venv

**For conda:**
```bash
python3.11 -m venv .venv

**Conda环境解决方案**:
```bash

Specify version explicitly

明确指定Python版本

conda create -n myenv python=3.11
undefined
conda create -n myenv python=3.11
undefined

Issue 4: Package conflicts

问题4:包冲突

For venv:
bash
undefined
venv环境解决方案
bash
undefined

Start fresh

重新创建环境

rm -rf .venv python -m venv .venv source .venv/bin/activate pip install -r requirements.txt

**For conda:**
```bash
rm -rf .venv python -m venv .venv source .venv/bin/activate pip install -r requirements.txt

**Conda环境解决方案**:
```bash

Try updating resolver

更新解析器

conda update -n base conda conda install -c conda-forge mamba # Faster solver mamba install package-name

---
conda update -n base conda conda install -c conda-forge mamba # 更快的解析器 mamba install package-name

---

Quick Reference

快速参考

Environment Detection Commands

环境检测命令

bash
undefined
bash
undefined

Check what's active

检查当前激活的环境

which python echo $VIRTUAL_ENV echo $CONDA_DEFAULT_ENV
which python echo $VIRTUAL_ENV echo $CONDA_DEFAULT_ENV

Python version

查看Python版本

python --version
python --version

Installed packages

查看已安装的包

pip list # for pip conda list # for conda
pip list # pip环境 conda list # conda环境

Environment location

查看包的安装位置

pip show package-name # shows where package is installed
undefined
pip show package-name # 显示包的安装路径
undefined

Activation Commands

环境激活命令

bash
undefined
bash
undefined

venv

venv环境

source .venv/bin/activate # Linux/Mac .venv\Scripts\activate # Windows
source .venv/bin/activate # Linux/Mac .venv\Scripts\activate # Windows

conda

conda环境

conda activate environment-name
conda activate environment-name

Deactivation

退出环境

deactivate # venv conda deactivate # conda

---
deactivate # venv conda deactivate # conda

---

Examples

示例

Example 1: Safe Installation Flow

示例1:安全安装流程

User: "Install requests"
Claude:
Let me check your environment first...

[Checks environment]

I see you're in a Python venv at: /home/user/project/.venv
Python version: 3.11.5

Is this the correct environment for installing requests?
User: "Yes"
Claude:
bash
pip install requests
用户: "安装requests"
回复:
我先检查一下您的环境...

[执行环境检测]

我检测到您当前处于以下Python venv环境:/home/user/project/.venv
Python版本:3.11.5

是否要使用此环境安装requests?
用户: "是"
执行命令:
bash
pip install requests

Example 2: No Environment Warning

示例2:无环境警告

User: "Install scikit-learn"
Claude:
⚠️ WARNING: No virtual environment detected!

You're using system Python at: /usr/bin/python3
Installing to system Python is not recommended.

This is a data science package. I suggest creating a conda environment:

conda create -n ml-project python=3.11
conda activate ml-project
conda install -c conda-forge scikit-learn

Would you like me to help set this up?
用户: "安装scikit-learn"
回复:
⚠️ 警告:未检测到虚拟环境!

您当前使用的是系统Python,路径为:/usr/bin/python3
不推荐向系统Python安装包。

这是一个数据科学包,我建议您创建conda环境:

conda create -n ml-project python=3.11
conda activate ml-project
conda install -c conda-forge scikit-learn

是否需要我协助您完成环境搭建?

Example 3: Environment Type Suggestion

示例3:环境类型建议

User: "I need to install biopython, numpy, and pandas"
Claude:
I notice you need scientific and bioinformatics packages.

Currently: No environment active

I recommend creating a conda environment because:
- Better binary dependency management for numpy/pandas
- Bioconda channel has biopython
- Manages versions more reliably

Suggested setup:
conda create -n bio-project python=3.11
conda activate bio-project
conda install -c conda-forge pandas numpy
conda install -c bioconda biopython

Would you like to proceed with this?

用户: "我需要安装biopython、numpy和pandas"
回复:
我注意到您需要安装科学计算和生物信息学相关的包。

当前状态:未检测到激活的环境

我建议您创建conda环境,原因如下:
- 对numpy/pandas等包的二进制依赖管理更出色
- biopython可通过bioconda频道获取
- 版本管理更可靠

推荐的搭建命令:
conda create -n bio-project python=3.11
conda activate bio-project
conda install -c conda-forge pandas numpy
conda install -c bioconda biopython

是否要按此方案执行?

Summary

总结

Always remember:
  1. Check environment before any installation
  2. Show user what environment is active
  3. Confirm with user before proceeding
  4. ⚠️ Warn if no environment is active
  5. 💡 Help choose appropriate environment type
  6. 📝 Document environment setup for reproducibility
Never:
  • ❌ Install without checking environment
  • ❌ Assume user wants to use system Python
  • ❌ Install without user confirmation
  • ❌ Skip warning about base conda environment
This skill ensures clean, reproducible, conflict-free Python environments across all projects.
请始终牢记:
  1. 安装前务必检查环境
  2. 告知用户当前激活的环境
  3. 操作前与用户确认
  4. ⚠️ 未检测到环境时发出警告
  5. 💡 协助用户选择合适的环境类型
  6. 📝 文档化环境搭建流程以确保可复现性
绝对不要:
  • ❌ 未检查环境就进行安装
  • ❌ 假设用户希望使用系统Python
  • ❌ 未获用户确认就执行安装
  • ❌ 跳过对conda base环境的警告
遵循以上实践可确保所有项目的Python环境整洁、可复现且无冲突。",