Python 环境管理指南:Conda & pip

一、Anaconda 安装与配置

1. 下载安装

通过 清华镜像源 下载合适版本,安装过程一路 Enter + yes 即可。

2. 配置 .bashrc

安装完成后,若终端未显示 (base),说明 conda 未被激活,需手动配置:

方法一:追加 PATH

1
2
echo 'export PATH="/home/user/anaconda3/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

方法二:创建 .bash_profile(与 .bashrc 同目录)

1
2
3
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi

创建后执行 source ~/.bash_profile 使其生效。

3. 换源(配置 .condarc

1
vim ~/.condarc

写入以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
channels:
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
- defaults
show_channel_urls: true

# 可选:公司内网代理配置
proxy_servers:
http: http://xxxx.com.cn:80
https: https://xxxx.com.cn:80

查看当前 conda 配置:

1
conda config --show

二、Conda 常用命令

操作 命令
新建环境 conda create -n env_name python=3.7
激活环境 conda activate env_name
退出环境 conda deactivate
删除环境 conda remove -n env_name --all
查看环境列表 conda env list
安装包 conda install pkg_name
导出环境 conda env export > env_name.yml
从 yml 新建 conda env create -f env_name.yml

三、pip 换源

1
mkdir ~/.pip && vim ~/.pip/pip.conf

写入以下内容:

1
2
3
4
5
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple

[install]
trusted-host = pypi.tuna.tsinghua.edu.cn

换源的必要性:

  • 官方源在国外,下载速度慢
  • 使用公司代理后直接访问官方源可能失败
  • 公司内网环境下需要指向内部镜像

本文参考:Python更换pip源方法过程解析-腾讯云开发者社区-腾讯云 (tencent.com)


四、搭建 Python 虚拟环境

方式 1:通过 requirements.txt

1
2
3
conda create -n myenv python=3.10
conda activate myenv
pip install -r requirements.txt

requirements.txt 示例:

1
2
3
4
numpy==1.24.0
pandas>=1.5.0
requests
flask==2.3.0

方式 2:通过 environment.yml

1
conda env create -f environment.yml

environment.yml 示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
name: my_env
channels:
- pytorch
- nvidia
- conda-forge
dependencies:
- python=3.9
- pytorch=2.0.*
- pytorch-cuda=11.8
- torchvision
- lightning=2.0.*
- pip
- pip:
- rootutils
- gdown==5.1.0

方式 3:可编辑安装(Editable Install)

适用于开发阶段将项目本身安装为可导入包,修改源码后立即生效,无需重新安装。

项目结构:

1
2
3
4
5
6
7
8
9
10
11
my_project/
├── __init__.py
├── aa/
│ ├── __init__.py ✅ 被识别为包
│ └── util/
│ ├── __init__.py ✅ 被识别为子包
│ └── box.py
├── bb/
│ └── module2.py ❌ 无 __init__.py,不会被识别
├── setup.py
└── environment.yml

setup.py 示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from setuptools import setup, find_packages

setup(
name="my_package",
version="0.1.0",
author="Your Name",
packages=find_packages(), # 自动查找所有含 __init__.py 的目录
install_requires=[
"numpy>=1.21",
"opencv-python",
],
entry_points={
"console_scripts": [
"mytool=mypkg.cli:main", # 安装后可用 `mytool` 命令
],
},
python_requires=">=3.7",
)

执行安装:

1
2
cd my_project/
pip install -e .

被安装的包有['my_project', 'aa', 'aa.util']。安装后,my_package 会以软链接方式注册到当前环境,路径指向源码目录,无需重复安装即可在该环境中全局导入。

验证 find_packages() 识别结果:

1
python -c "from setuptools import find_packages; print(find_packages())"

参考文章:https://zhuanlan.zhihu.com/p/98007747