安装
curl -LsSf https://astral.sh/uv/install.sh | sh
使用
建议创建目录结构为
my_project/
├── pyproject.toml # 项目配置(依赖、脚本、元数据)
├── README.md # 项目说明文档
├── LICENSE # 开源协议(如 MIT、Apache)
├── .gitignore # Git 忽略文件配置
├── src/
│ └── my_project/ # 源代码包(模块化结构)
│ ├── __init__.py # 包初始化文件
│ └── main.py # 主逻辑入口
├── tests/ # 单元测试 & 集成测试
│ ├── __init__.py
│ └── test_main.py
├── docs/ # 文档目录(可选)
├── scripts/ # 存放部署或构建脚本
└── .pre-commit-config.yaml # pre-commit hooks 配置(可选)
创建项目
初始化项目
uv init my_project
cd my_project
pyproject.toml
[project]
name = "my_project"
version = "0.1.0"
description = ""
requires-python = ">=3.8"
dependencies = []
[build-system]
requires = ["setuptools>=42"]
build-backend = "setuptools.build_meta"
安装依赖
uv install
运行
uv run python -m my_project.main
或添加可执行脚本参数到 pyproject.toml
[project.scripts]
my-app = "my_project.main:main"
再运行
uv run my-app
相关命令行
手动创建 src/my_project/
目录结构
mkdir -p src/my_project
touch src/my_project/__init__.py
touch src/my_project/main.py
添加测试目录
mkdir tests
touch tests/__init__.py
touch tests/test_main.py
配置 pyproject.toml
[project]
name = "my_project"
version = "0.1.0"
description = "A sample project"
requires-python = ">=3.8"
dependencies = [
"requests",
]
[build-system]
requires = ["setuptools>=42"]
build-backend = "setuptools.build_meta"
[project.scripts]
my-cli = "my_project.main:main" # 命令行接口
安装依赖并运行
uv install
uv run my-cli
src/my_project/main.py
def main():
print("Hello from my_project!")
if __name__ == "__main__":
main()
tests/test_main.py
from my_project.main import main
def test_main(capsys):
main()
captured = capsys.readouterr()
assert "Hello from my_project!" in captured.out
或者
文件内容为:
src/my_project/__main__.py
import sys
import my_project
sys.exit(my_project.main())
src/my_project/__init__.py
def main():
print("Hello from my_project!")
if __name__ == "__main__":
main()
pyproject.toml
[project.scripts]
my_project = "my_project:main"