Skip to content

项目依赖管理

pip

Python pip 包管理

基本 pip 命令

bash
# 安装包
pip install requests
pip install numpy pandas matplotlib

# 安装特定版本
pip install requests==2.28.1
pip install "requests>=2.25.0,<3.0.0"

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

# 卸载包
pip uninstall requests

# 升级包
pip install --upgrade requests
pip install -U requests

# 列出已安装的包
pip list
pip freeze

# 查看包信息
pip show requests

# 搜索包
pip search requests  # 注意:此功能已被禁用

# 检查过时的包
pip list --outdated

# 生成 requirements.txt
pip freeze > requirements.txt

requirements.txt 文件

txt
# requirements.txt 示例
# Web 框架
Flask==2.3.3
Django==4.2.4

# 数据处理
numpy==1.24.3
pandas==2.0.3
matplotlib==3.7.2

# 网络请求
requests==2.31.0
urllib3==2.0.4

# 数据库
SQLAlchemy==2.0.20
psycopg2-binary==2.9.7

# 测试框架
pytest==7.4.0
pytest-cov==4.1.0

# 开发工具
black==23.7.0
flake8==6.0.0
mypy==1.5.1

# 可选依赖
# redis==4.6.0
# celery==5.3.1

pip 配置文件

ini
# pip.conf (Linux/macOS) 或 pip.ini (Windows)
[global]
index-url = https://pypi.org/simple/
trusted-host = pypi.org
timeout = 60
retries = 3

[install]
user = false
no-deps = false

[uninstall]
yes = false

venv 和 conda

Python 虚拟环境

venv 虚拟环境

bash
# 创建虚拟环境
python -m venv myenv
python3 -m venv myenv

# 激活虚拟环境
# Windows
myenv\Scripts\activate

# macOS/Linux
source myenv/bin/activate

# 退出虚拟环境
deactivate

# 删除虚拟环境
rm -rf myenv  # Linux/macOS
rmdir /s myenv  # Windows

# 在虚拟环境中安装包
pip install requests numpy

# 查看虚拟环境信息
which python  # Linux/macOS
where python  # Windows

conda 环境管理

bash
# 创建 conda 环境
conda create -n myenv python=3.9
conda create -n myenv python=3.9 numpy pandas

# 激活环境
conda activate myenv

# 退出环境
conda deactivate

# 列出所有环境
conda env list
conda info --envs

# 删除环境
conda env remove -n myenv

# 导出环境
conda env export > environment.yml

# 从文件创建环境
conda env create -f environment.yml

# 安装包
conda install numpy pandas
conda install -c conda-forge jupyter

# 查看已安装的包
conda list

environment.yml 文件

yaml
# environment.yml 示例
name: myproject
channels:
  - conda-forge
  - defaults
dependencies:
  - python=3.9
  - numpy=1.24.3
  - pandas=2.0.3
  - matplotlib=3.7.2
  - jupyter
  - pip
  - pip:
      - requests==2.31.0
      - flask==2.3.3

poetry

Python Poetry 依赖管理

安装和初始化

bash
# 安装 Poetry
curl -sSL https://install.python-poetry.org | python3 -

# 初始化新项目
poetry new myproject
cd myproject

# 在现有项目中初始化
poetry init

# 添加依赖
poetry add requests
poetry add numpy pandas
poetry add --dev pytest black

# 安装依赖
poetry install

# 运行脚本
poetry run python main.py
poetry run pytest

# 激活虚拟环境
poetry shell

pyproject.toml 文件

toml
# pyproject.toml 示例
[tool.poetry]
name = "myproject"
version = "0.1.0"
description = "我的 Python 项目"
authors = ["Your Name <your.email@example.com>"]
readme = "README.md"
packages = [{include = "myproject"}]

[tool.poetry.dependencies]
python = "^3.9"
requests = "^2.31.0"
numpy = "^1.24.3"
pandas = "^2.0.3"

[tool.poetry.group.dev.dependencies]
pytest = "^7.4.0"
black = "^23.7.0"
flake8 = "^6.0.0"
mypy = "^1.5.1"

[tool.poetry.group.test.dependencies]
pytest-cov = "^4.1.0"
pytest-mock = "^3.11.1"

[tool.poetry.scripts]
start = "myproject.main:main"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

[tool.black]
line-length = 88
target-version = ['py39']

[tool.mypy]
python_version = "3.9"
warn_return_any = true
warn_unused_configs = true

Poetry 高级功能

bash
# 更新依赖
poetry update
poetry update requests

# 显示依赖树
poetry show --tree

# 导出 requirements.txt
poetry export -f requirements.txt --output requirements.txt

# 发布包
poetry build
poetry publish

# 检查依赖冲突
poetry check

# 锁定依赖版本
poetry lock

JavaScript 依赖管理

npm 包管理

基本 npm 命令

bash
# 初始化项目
npm init
npm init -y

# 安装包
npm install express
npm install lodash axios
npm i express  # 简写

# 安装开发依赖
npm install --save-dev jest
npm install -D eslint prettier

# 安装全局包
npm install -g nodemon
npm install -g typescript

# 安装特定版本
npm install express@4.18.2
npm install "express>=4.0.0,<5.0.0"

# 卸载包
npm uninstall express
npm remove express

# 更新包
npm update
npm update express

# 列出已安装的包
npm list
npm list --depth=0

# 查看包信息
npm info express

package.json 文件

json
{
  "name": "myproject",
  "version": "1.0.0",
  "description": "我的 JavaScript 项目",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "jest",
    "test:watch": "jest --watch",
    "lint": "eslint src/",
    "lint:fix": "eslint src/ --fix",
    "format": "prettier --write src/",
    "build": "webpack --mode production",
    "build:dev": "webpack --mode development"
  },
  "keywords": ["nodejs", "express", "api"],
  "author": "Your Name <your.email@example.com>",
  "license": "MIT",
  "dependencies": {
    "express": "^4.18.2",
    "cors": "^2.8.5",
    "helmet": "^7.0.0",
    "morgan": "^1.10.0",
    "dotenv": "^16.3.1",
    "mongoose": "^7.4.3",
    "bcryptjs": "^2.4.3",
    "jsonwebtoken": "^9.0.2"
  },
  "devDependencies": {
    "nodemon": "^3.0.1",
    "jest": "^29.6.2",
    "supertest": "^6.3.3",
    "eslint": "^8.47.0",
    "prettier": "^3.0.2",
    "@types/node": "^20.5.0",
    "@types/express": "^4.17.17"
  },
  "engines": {
    "node": ">=16.0.0",
    "npm": ">=8.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/username/myproject.git"
  },
  "bugs": {
    "url": "https://github.com/username/myproject/issues"
  },
  "homepage": "https://github.com/username/myproject#readme"
}

Yarn 包管理

bash
# 安装 Yarn
npm install -g yarn

# 初始化项目
yarn init
yarn init -y

# 安装包
yarn add express
yarn add lodash axios
yarn add --dev jest

# 安装全局包
yarn global add nodemon

# 安装特定版本
yarn add express@4.18.2

# 卸载包
yarn remove express

# 更新包
yarn upgrade
yarn upgrade express

# 列出已安装的包
yarn list

# 运行脚本
yarn start
yarn test
yarn build

pnpm 包管理

bash
# 安装 pnpm
npm install -g pnpm

# 初始化项目
pnpm init

# 安装包
pnpm add express
pnpm add -D jest

# 安装全局包
pnpm add -g nodemon

# 运行脚本
pnpm start
pnpm test

依赖管理最佳实践

Python 最佳实践

python
# setup.py 示例
from setuptools import setup, find_packages

setup(
    name="myproject",
    version="0.1.0",
    description="我的 Python 项目",
    author="Your Name",
    author_email="your.email@example.com",
    packages=find_packages(),
    install_requires=[
        "requests>=2.25.0",
        "numpy>=1.20.0",
        "pandas>=1.3.0",
    ],
    extras_require={
        "dev": [
            "pytest>=6.0",
            "black>=21.0",
            "flake8>=3.8",
        ],
        "test": [
            "pytest-cov>=2.10",
            "pytest-mock>=3.6",
        ],
    },
    python_requires=">=3.8",
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
    ],
)

JavaScript 最佳实践

javascript
// .npmrc 配置文件
registry=https://registry.npmjs.org/
save-exact=true
package-lock=true
audit=false
fund=false

// .yarnrc 配置文件
registry "https://registry.npmjs.org/"
save-exact true

依赖管理对比

特性PythonJavaScript
包管理器pip, conda, poetrynpm, yarn, pnpm
配置文件requirements.txt, pyproject.tomlpackage.json
虚拟环境venv, condanode_modules
锁定文件poetry.lockpackage-lock.json, yarn.lock
开发依赖pip install -enpm install --save-dev
全局安装pip install -gnpm install -g

项目结构示例

Python 项目结构

myproject/
├── pyproject.toml
├── poetry.lock
├── requirements.txt
├── setup.py
├── README.md
├── .gitignore
├── src/
│   └── myproject/
│       ├── __init__.py
│       ├── main.py
│       └── utils.py
├── tests/
│   ├── __init__.py
│   ├── test_main.py
│   └── test_utils.py
├── docs/
│   └── README.md
└── scripts/
    ├── setup.sh
    └── deploy.sh

JavaScript 项目结构

myproject/
├── package.json
├── package-lock.json
├── .npmrc
├── README.md
├── .gitignore
├── src/
│   ├── index.js
│   ├── utils.js
│   └── config.js
├── tests/
│   ├── index.test.js
│   └── utils.test.js
├── docs/
│   └── README.md
├── scripts/
│   ├── setup.sh
│   └── deploy.sh
└── .eslintrc.js

练习

  1. 创建一个 Python 项目,使用 poetry 管理依赖

参考答案:

bash
poetry new myproject
cd myproject
poetry add requests
  1. 创建一个 JavaScript 项目,使用 npm 管理依赖

参考答案:

bash
mkdir my-js-project
cd my-js-project
npm init -y
npm install axios
  1. 设置虚拟环境并安装常用开发工具

参考答案:

bash
# Python
python -m venv venv
source venv/bin/activate  # Windows 用 venv\Scripts\activate
pip install black flake8 pytest

# JavaScript
npm install --save-dev eslint prettier jest
  1. 创建 requirements.txt 和 package.json 文件

参考答案:

bash
# Python
pip freeze > requirements.txt

# JavaScript
npm init -y  # 自动生成 package.json
  1. 比较不同包管理器的优缺点

参考答案:

  • pip 简单易用,生态丰富,适合 Python。
  • poetry 现代化,支持依赖锁定和虚拟环境。
  • npm/yarn/pnpm 适合 JavaScript,依赖树清晰,支持锁定和脚本。
  • pnpm 节省磁盘空间,速度快。

下一步

现在你已经了解了项目依赖管理,接下来我们将学习类型系统。