项目构建工具
Python项目构建工具有很多种,其中一些常用的包括:
- setuptools:这是一个用于构建、分发和安装Python软件包的工具。它可以帮助你定义项目的结构、依赖关系和安装步骤。
- pipenv:这是一个结合了pip和虚拟环境管理的工具,可以简化项目依赖管理的过程,同时创建独立的虚拟环境。
- Poetry:Poetry是一个现代化的Python包管理工具,它提供了依赖管理、打包发布等功能,并且有一个易于使用的配置文件格式。
- tox:如果你需要在不同的Python版本下运行测试或构建项目,tox是一个很好的选择。它可以帮助你自动化这些任务,确保项目在不同环境下都能正常工作。
Poetry
Poetry是一个现代化的Python包管理工具,它提供了依赖管理、打包发布等功能,并且有一个易于使用的配置文件格式。
安装Poetry
创建新项目
使用以下命令创建一个名字为 my_project 的Poetry新项目
1 2
| $ poetry new <my_project> $ cd <my_project>
|
配置依赖项
pyproject.toml
文件是用于定义Python项目元数据和构建配置的文件,通常与现代Python构建工具(如Poetry)一起使用。记录项目信息
这个部分用于指定Poetry项目的元数据,包括项目名称、版本、描述和作者等信息。
1 2 3 4 5
| [tool.poetry] name = "my_project" version = "0.1.0" description = "My Python project" authors = ["Your Name <you@example.com>"]
|
这里定义项目的生产依赖项,可以指定Python版本和其他必需的包。
1 2 3 4
| [tool.poetry.dependencies] python = "^3.8" requests = "^2.25.1"
|
这里定义项目的开发依赖项,通常用于测试、文档生成等开发过程中需要但不会包含在最终发布中的包。
1 2
| [tool.poetry.dev-dependencies] pytest = "^6.2"
|
这个部分用于定义项目的命令行脚本。
1 2 3
| [tool.poetry.scripts] my_script = "my_package.my_module:main"
|
这个部分用于定义项目的可选依赖项。
1 2 3
| [tool.poetry.extras] dev = ["pytest", "flake8"]
|
[build-system] 部分
1 2 3 4
| [build-system] requires = ["poetry>=1.0"] build-backend = "poetry.masonry.api"
|
进入项目环境
添加依赖项
安装依赖项
移除依赖项
1
| $ poetry remove <package-name>
|
更新依赖项
更新锁文件
查询依赖 - 显示依赖树的功能
1 2 3
| $ poetry show -t
$ poetry show -t <package-name>
|
管理虚拟环境
1 2 3 4 5 6 7 8
| $ poetry env use python3.8
$ poetry shell
$ poetry install
|
构建和发布
1 2 3 4 5
| poetry build
poetry publish
|
与其他工具集成
Docker 集成
- 创建 Dockerfile:在项目根目录下创建一个 Dockerfile,用于构建 Docker 镜像
1 2 3 4 5 6 7 8 9 10 11 12 13
| FROM python:3.8
WORKDIR /app
COPY pyproject.toml poetry.lock ./
RUN pip install poetry RUN poetry install
COPY . .
CMD ["poetry", "run", "your_main_script.py"]
|
- 构建 Docker 镜像
1
| $ docker build -t my_project .
|
- 运行 Docker 容器
CI/CD 工具集成(以GitHub Actions为例)
- 创建 Workflow 文件:在项目中的
.github/workflows
目录下创建一个 YAML 文件,例如 ci.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
name: CI
on: push: branches: - main
jobs: build: runs-on: ubuntu-latest
steps: - name: Checkout code uses: actions/checkout@v2
- name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.8
- name: Install dependencies run: poetry install
- name: Run tests run: poetry run pytest
|
- 配置依赖项:在
pyproject.toml
文件中添加 dev-dependencies
,以确保在 CI/CD 环境中安装所需的依赖项。
1 2 3 4
|
[tool.poetry.dev-dependencies] pytest = "^6.2.4"
|
提交代码:将 Workflow 文件和更新的 pyproject.toml
文件提交到 GitHub 仓库中。
启用 GitHub Actions:在 GitHub 仓库的 Actions 选项卡中启用 Actions。每次推送到 main
分支时,GitHub Actions 将自动运行自动化测试。
Pipenv