Appearance
Python 项目管理最佳实践
使用 poetry
来管理项目依赖是一个很好的选择,它可以帮助开发者指定、安装和解决项目中的外部包。
- (可选)安装
poetry
:
推荐配套使用 Python 3.10+,以下指令可在 Ubuntu 20.04 LTS 上安装 Python 3.10:
bash
# Prerequisite
sudo apt update
# Add custom APT repository
sudo apt install software-properties-common -y
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
# Install Python 3.10
sudo apt install python3.10 python3.10-venv python3.10-dev
python3 --version
# Caution: This may cause problem with terminal not open on Ubuntu
sudo ln -sf /usr/bin/python3.10 /usr/bin/python3
python3 --version
# Install pip for Python 3.10
curl -sS https://bootstrap.pypa.io/get-pip.py | python3.10
python3.10 -m pip --version
安装 poetry
前推荐安装 pipx
工具:
bash
python3 -m pip install --user pipx
python3 -m pipx ensurepath
# (optional) To allow pipx actions in global scope.
sudo pipx ensurepath --global
# (optional) To prepend the pipx bin directory to PATH instead of appending it.
sudo pipx ensurepath --prepend
安装 poetry
:
bash
pipx install poetry
# (optional) Enable tab completion for Bash.
poetry completions bash >> ~/.bash_completion
# (optional) Enable tab completion for Oh My Zsh.
mkdir $ZSH_CUSTOM/plugins/poetry
- 使用
poetry
创建新项目:
bash
poetry new ${project_name}
cd ${project_name}
# The virtualenv will be created inside the project path and vscode will recognize it.
poetry config virtualenvs.in-project true
poetry env use 3.10
- 指定 Python 版本: 在
pyproject.toml
文件中,开发者可以指定项目所需的 Python 版本,例如:
pyproject.toml
[tool.poetry.dependencies]
python = "^3.10"
- 添加项目依赖
bash
poetry add stable-ts
pyproject.toml
[tool.poetry.dependencies]
python = "^3.10"
stable-ts = "^2.17.2"
- 安装依赖
bash
poetry install
- 拉起装载依赖的虚拟环境
bash
poetry shell