环境配置指南¶
本指南将帮助你从零开始配置机器人开发环境,包括操作系统、开发工具、Python 环境等。
学习目标¶
完成本章后,你将能够:
- 安装和配置 WSL2(Windows 用户)
- 安装和配置 Docker
- 配置 Python 开发环境
- 安装 ROS 开发环境
- 使用基本的开发工具
1. 操作系统配置¶
1.1 Windows 用户:安装 WSL2¶
WSL2(Windows Subsystem for Linux 2)允许你在 Windows 上运行 Linux 环境。
什么是 WSL2?¶
WSL2 的优势:
- 在 Windows 上运行完整的 Linux 内核
- 与 Windows 无缝集成
- 支持 GPU 加速
- 支持 Docker
- 性能接近原生 Linux
适用场景:
- 机器人开发(ROS 需要 Linux)
- 深度学习开发
- 服务器端开发
安装步骤¶
# 1. 以管理员身份打开 PowerShell
# 2. 启用 WSL 功能
wsl --install
# 3. 重启电脑
# 4. 设置用户名和密码
# 5. 更新 WSL
wsl --update
# 6. 查看 WSL 版本
wsl --version
安装 Ubuntu¶
# 查看可用的 Linux 发行版
wsl --list --online
# 安装 Ubuntu 22.04
wsl --install -d Ubuntu-22.04
# 设置默认版本
wsl --set-default-version 2
配置 WSL2¶
# 在 WSL2 中更新系统
sudo apt update && sudo apt upgrade -y
# 安装基本工具
sudo apt install -y build-essential git curl wget
# 安装 Python
sudo apt install -y python3 python3-pip python3-venv
# 配置 Git
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
WSL2 基础知识¶
# 文件系统
# Windows 文件:/mnt/c/, /mnt/d/, etc.
# Linux 文件:/home/username/
# 访问 Windows 文件
cd /mnt/c/Users/YourName/Desktop
# 从 Windows 访问 Linux 文件
# 在文件资源管理器中输入:\\wsl$
# 环境变量
# Windows 环境变量在 WSL2 中可用
echo $PATH
# 网络
# WSL2 使用独立的 IP 地址
# 可以通过 localhost 访问 Windows 服务
1.2 macOS 用户¶
# 安装 Homebrew(包管理器)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# 安装基本工具
brew install git curl wget python3
# 安装 Xcode 命令行工具
xcode-select --install
1.3 Linux 用户¶
# Ubuntu/Debian
sudo apt update
sudo apt install -y build-essential git curl wget python3 python3-pip
# CentOS/RHEL
sudo yum groupinstall "Development Tools"
sudo yum install git curl wget python3
# Arch Linux
sudo pacman -S base-devel git curl wget python
2. Docker 安装与配置¶
2.1 什么是 Docker?¶
Docker 是一个容器化平台,可以:
- 打包应用及其依赖
- 在任何环境中运行一致
- 简化部署和扩展
- 隔离不同项目环境
容器 vs 虚拟机:
┌─────────────┐ ┌─────────────┐
│ 容器 │ │ 虚拟机 │
├─────────────┤ ├─────────────┤
│ 应用 │ │ 应用 │
│ 依赖 │ │ 依赖 │
│ 容器运行时 │ │ Guest OS │
│ │ │ Hypervisor│
│ 主机 OS │ │ 主机 OS │
└─────────────┘ └─────────────┘
2.2 安装 Docker¶
Windows(使用 WSL2)¶
# 1. 下载 Docker Desktop
# https://www.docker.com/products/docker-desktop/
# 2. 安装 Docker Desktop
# 3. 启用 WSL2 后端
# 在 Docker Desktop 设置中启用 "Use the WSL 2 based engine"
# 4. 配置 WSL2 集成
# Settings -> Resources -> WSL Integration
# 启用你的 Ubuntu 发行版
macOS¶
# 方法 1:使用 Homebrew
brew install --cask docker
# 方法 2:下载 Docker Desktop
# https://www.docker.com/products/docker-desktop/
Linux¶
# Ubuntu/Debian
# 1. 更新包索引
sudo apt update
# 2. 安装依赖
sudo apt install -y apt-transport-https ca-certificates curl software-properties-common
# 3. 添加 Docker GPG 密钥
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
# 4. 添加 Docker 仓库
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
# 5. 安装 Docker
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
# 6. 将用户添加到 docker 组
sudo usermod -aG docker $USER
# 7. 重启或运行
newgrp docker
2.3 Docker 基础知识¶
# 验证安装
docker --version
docker-compose --version
# 运行第一个容器
docker run hello-world
# 查看运行中的容器
docker ps
# 查看所有容器
docker ps -a
# 查看镜像
docker images
2.4 Docker 常用命令¶
# 镜像操作
docker pull ubuntu:22.04 # 拉取镜像
docker build -t myapp . # 构建镜像
docker rmi myapp # 删除镜像
# 容器操作
docker run -it ubuntu:22.04 bash # 运行交互式容器
docker run -d myapp # 后台运行容器
docker stop container_id # 停止容器
docker start container_id # 启动容器
docker rm container_id # 删除容器
# 数据卷
docker run -v /host/path:/container/path myapp # 挂载数据卷
docker volume create myvolume # 创建数据卷
# 网络
docker network create mynetwork # 创建网络
docker run --network mynetwork myapp # 使用网络
2.5 Dockerfile 示例¶
# 基础镜像
FROM ubuntu:22.04
# 设置工作目录
WORKDIR /app
# 安装依赖
RUN apt-get update && apt-get install -y \
python3 \
python3-pip \
&& rm -rf /var/lib/apt/lists/*
# 复制文件
COPY requirements.txt .
# 安装 Python 依赖
RUN pip3 install -r requirements.txt
# 复制应用代码
COPY . .
# 暴露端口
EXPOSE 8000
# 运行应用
CMD ["python3", "app.py"]
2.6 Docker Compose¶
# docker-compose.yml
version: '3.8'
services:
web:
build: .
ports:
- "8000:8000"
volumes:
- .:/app
depends_on:
- db
db:
image: postgres:14
environment:
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
3. Python 环境配置¶
3.1 安装 Anaconda/Miniconda¶
# 下载 Miniconda
# https://docs.conda.io/en/latest/miniconda.html
# Linux/macOS
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
# Windows(在 WSL2 中)
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
3.2 创建虚拟环境¶
# 创建环境
conda create -n robotics python=3.10
# 激活环境
conda activate robotics
# 查看环境列表
conda env list
# 删除环境
conda env remove -n robotics
3.3 安装 Python 包¶
# 使用 conda 安装
conda install numpy pandas matplotlib
# 使用 pip 安装
pip install numpy pandas matplotlib
# 使用国内镜像(中国用户)
pip install numpy pandas matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
# 从 requirements.txt 安装
pip install -r requirements.txt
# 导出 requirements.txt
pip freeze > requirements.txt
3.4 安装 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
# 验证安装
python -c "import torch; print(torch.__version__); print(torch.cuda.is_available())"
3.5 Jupyter Notebook¶
# 安装 Jupyter
pip install jupyter
# 启动 Jupyter
jupyter notebook
# 或者使用 JupyterLab
pip install jupyterlab
jupyter lab
4. 开发工具配置¶
4.1 VS Code¶
# 下载 VS Code
# https://code.visualstudio.com/
# 安装扩展
# - Python
# - Jupyter
# - Remote - WSL
# - Docker
# - C/C++
4.2 Git 配置¶
# 安装 Git
# Windows: https://git-scm.com/download/win
# macOS: brew install git
# Linux: sudo apt install git
# 配置 Git
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# 生成 SSH 密钥
ssh-keygen -t ed25519 -C "your.email@example.com"
# 添加到 SSH 代理
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
# 复制公钥
cat ~/.ssh/id_ed25519.pub
# 添加到 GitHub/GitLab
4.3 终端配置¶
# 安装 Oh My Zsh(可选)
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
# 安装 Powerlevel10k 主题(可选)
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k
# 配置 .zshrc
ZSH_THEME="powerlevel10k/powerlevel10k"
plugins=(git docker kubectl)
5. ROS 环境配置¶
5.1 安装 ROS Noetic(Ubuntu 20.04)¶
# 1. 设置 sources.list
sudo sh -c 'echo "deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros-latest.list'
# 2. 设置密钥
curl -s https://raw.githubusercontent.com/ros/rosdistro/master/ros.asc | sudo apt-key add -
# 3. 更新包索引
sudo apt update
# 4. 安装 ROS
sudo apt install ros-noetic-desktop-full
# 5. 设置环境
echo "source /opt/ros/noetic/setup.bash" >> ~/.bashrc
source ~/.bashrc
# 6. 安装依赖工具
sudo apt install python3-rosdep python3-rosinstall python3-rosinstall-generator python3-wstool build-essential
# 7. 初始化 rosdep
sudo rosdep init
rosdep update
5.2 安装 ROS 2 Humble(Ubuntu 22.04)¶
# 1. 设置 locale
sudo apt update && sudo apt install locales
sudo locale-gen en_US en_US.UTF-8
sudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8
export LANG=en_US.UTF-8
# 2. 设置 sources
sudo apt install software-properties-common
sudo add-apt-repository universe
# 3. 添加 ROS 2 GPG 密钥
sudo apt update && sudo apt install curl -y
sudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o /usr/share/keyrings/ros-archive-keyring.gpg
# 4. 添加仓库
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/ros-archive-keyring.gpg] http://packages.ros.org/ros2/ubuntu $(. /etc/os-release && echo $UBUNTU_CODENAME) main" | sudo tee /etc/apt/sources.list.d/ros2.list > /dev/null
# 5. 安装 ROS 2
sudo apt update
sudo apt install ros-humble-desktop
# 6. 设置环境
echo "source /opt/ros/humble/setup.bash" >> ~/.bashrc
source ~/.bashrc
5.3 创建 ROS 工作空间¶
# 创建工作空间
mkdir -p ~/catkin_ws/src
cd ~/catkin_ws
# 初始化工作空间
catkin_make
# 设置环境
echo "source ~/catkin_ws/devel/setup.bash" >> ~/.bashrc
source ~/.bashrc
6. 基础小知识¶
6.1 Linux 基础命令¶
# 文件操作
ls -la # 列出文件
cd /path/to/dir # 切换目录
pwd # 显示当前目录
mkdir -p dir1/dir2 # 创建目录
rm -rf dir # 删除目录
cp -r src dst # 复制文件
mv src dst # 移动文件
# 文件查看
cat file.txt # 查看文件
less file.txt # 分页查看
head -n 10 file.txt # 查看前10行
tail -n 10 file.txt # 查看后10行
# 搜索
grep "pattern" file.txt # 搜索文本
find . -name "*.py" # 查找文件
# 权限
chmod +x script.sh # 添加执行权限
chmod 755 file # 设置权限
# 系统信息
uname -a # 系统信息
df -h # 磁盘使用
free -h # 内存使用
top # 进程监控
6.2 Python 基础¶
# 变量和数据类型
x = 10 # 整数
y = 3.14 # 浮点数
name = "Robot" # 字符串
is_valid = True # 布尔值
numbers = [1, 2, 3] # 列表
info = {"name": "Robot"} # 字典
# 函数
def greet(name):
"""问候函数"""
return f"Hello, {name}!"
# 类
class Robot:
def __init__(self, name):
self.name = name
def move(self):
print(f"{self.name} is moving")
# 异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Done")
6.3 Git 基础¶
# 初始化仓库
git init
# 克隆仓库
git clone https://github.com/user/repo.git
# 查看状态
git status
# 添加文件
git add .
# 提交
git commit -m "Initial commit"
# 推送
git push origin main
# 拉取
git pull origin main
# 分支
git branch feature # 创建分支
git checkout feature # 切换分支
git merge feature # 合并分支
6.4 Docker 基础¶
# 运行容器
docker run -it ubuntu:22.04 bash
# 查看容器
docker ps
# 停止容器
docker stop container_id
# 删除容器
docker rm container_id
# 查看镜像
docker images
# 删除镜像
docker rmi image_id
7. 常见问题¶
1. WSL2 安装失败¶
问题:WSL2 安装失败
解决方案:
# 启用虚拟化
# 在 BIOS 中启用 Intel VT-x 或 AMD-V
# 启用 Windows 功能
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
# 设置默认版本
wsl --set-default-version 2
2. Docker 权限问题¶
问题:Docker 命令需要 sudo
解决方案:
3. Python 包安装失败¶
问题:pip 安装失败
解决方案:
# 使用国内镜像
pip install package -i https://pypi.tuna.tsinghua.edu.cn/simple
# 升级 pip
pip install --upgrade pip
# 使用 conda
conda install package
4. ROS 安装失败¶
问题:ROS 安装失败
解决方案:
# 检查 Ubuntu 版本
lsb_release -a
# 清理缓存
sudo apt clean
sudo apt update
# 手动添加密钥
sudo apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654
8. 下一步¶
配置完环境后,你可以: