Skip to content

Python 环境配置

Python 是机器人开发的核心语言。本节专注于 Python 环境的配置。

1. 安装 Python

大多数系统已预装 Python 3。检查版本:

python3 --version

如果没有安装或版本太旧:

# Ubuntu / Debian
sudo apt install -y python3 python3-pip python3-venv

# macOS
brew install python3

2. 安装 Conda

Conda 是 Python 的包和环境管理器,推荐使用轻量的 Miniconda

# 下载 Miniconda
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh

# 安装(按提示操作)
bash Miniconda3-latest-Linux-x86_64.sh

# 重新加载 shell
source ~/.bashrc

验证

conda --version

3. 创建虚拟环境

# 创建环境(指定 Python 版本)
conda create -n robotics python=3.10

# 激活环境
conda activate robotics

# 查看所有环境
conda env list

# 退出环境
conda deactivate

# 删除环境
conda env remove -n robotics

为什么要用虚拟环境?

不同项目可能需要不同版本的包。虚拟环境让每个项目有独立的依赖,互不干扰。

4. 安装 Python 包

# 激活环境
conda activate robotics

# 使用 pip 安装
pip install numpy pandas matplotlib opencv-python

# 使用 conda 安装
conda install numpy pandas matplotlib

# 从 requirements.txt 批量安装
pip install -r requirements.txt

# 导出当前环境的依赖
pip freeze > requirements.txt

国内镜像加速(中国用户)

# 临时使用
pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple

# 永久配置
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

5. 安装 PyTorch

# CPU 版本
pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu

# GPU 版本(CUDA 11.8)
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118

# GPU 版本(CUDA 12.1)
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121

验证 GPU

# 查看 GPU 信息
nvidia-smi

# 验证 PyTorch CUDA
python -c "import torch; print(f'PyTorch: {torch.__version__}'); print(f'CUDA: {torch.cuda.is_available()}')"

6. Jupyter Notebook

Jupyter 是交互式编程环境,适合数据探索和学习。

# 安装
pip install jupyterlab

# 启动
jupyter lab
# 浏览器会自动打开 http://localhost:8888

VS Code 中使用 Jupyter

  1. 安装 VS Code 的 Jupyter 扩展
  2. 打开 .ipynb 文件即可直接编辑运行

7. 第一个 Python 程序

创建 hello.py

import numpy as np
import torch

# NumPy
arr = np.array([1, 2, 3, 4, 5])
print(f"NumPy array: {arr}")
print(f"Mean: {arr.mean()}")

# PyTorch
tensor = torch.tensor([1.0, 2.0, 3.0])
print(f"PyTorch tensor: {tensor}")
print(f"GPU available: {torch.cuda.is_available()}")

运行:

python hello.py

常见问题

pip 安装超时

pip install --timeout 1000 numpy -i https://pypi.tuna.tsinghua.edu.cn/simple

conda 环境激活失败

# 初始化 conda
conda init bash   # 或 zsh
source ~/.bashrc

PyTorch 找不到 CUDA

# 确认 CUDA 版本匹配
nvidia-smi                         # 查看 CUDA 版本
pip install torch --index-url https://download.pytorch.org/whl/cu118  # 选择对应版本

下一步


← 返回总览 | 下一页:Docker 配置 →