将Python包发布至PyPI的完整流程
配置PyPI账户与上传凭证
在发布前,需先在 PyPI官网 注册账号,并为本地工具配置认证信息。创建或修改用户主目录下的 .pypirc 文件:
vim ~/.pypirc
填入以下内容:
[distutils]
index-servers = pypi
[pypi]
repository: https://upload.pypi.org/legacy/
username: your_pypi_username
password: your_pypi_password
注意:自2023年起,建议使用API token代替明文密码以提升安全性。
标准项目结构设计
一个符合PyPI发布的典型Python项目应包含如下结构:
.
├── LICENSE
├── MANIFEST.in
├── README.md
├── mypackage
│ └── __init__.py
├── setup.py
└── tests
└── test_mypackage.py
若开发的是pytest插件,则结构略有不同:
├── pytest_custom_marker
│ ├── __init__.py
│ └── plugin.py
├── setup.py
└── tests
└── test_plugin.py
推荐使用
cookiecutter工具基于模板快速生成专业结构,例如通过命令:
pip install cookiecutter
再执行:
cookiecutter gh:audreyr/cookiecutter-pypackage
编写setup.py配置文件
该文件是打包的核心,定义了包的元数据和依赖关系。基础版本示例如下:
import os
from setuptools import setup, find_packages
def load_readme():
here = os.path.abspath(os.path.dirname(__file__))
readme_path = os.path.join(here, 'README.md')
with open(readme_path, 'r', encoding='utf-8') as f:
return f.read()
setup(
name='mypackage',
version='0.1.0',
author='Your Name',
author_email='your.email@example.com',
description='A short summary of the package',
long_description=load_readme(),
long_description_content_type='text/markdown',
url='https://github.com/yourname/mypackage',
packages=find_packages(include=['mypackage']),
include_package_data=True,
python_requires='>=3.6',
install_requires=[],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
],
)
针对pytest插件的特殊配置
若构建的是pytest扩展,需在 setup.py 中声明入口点:
setup(
name='pytest-custom-marker',
version='0.1.0',
packages=find_packages(include=['pytest_custom_marker']),
install_requires=['pytest'],
entry_points={
'pytest11': [
'custom_marker = pytest_custom_marker.plugin'
]
},
# 其他字段...
)
其中 pytest11 是pytest识别插件的关键命名空间,确保其正确注册后,pytest运行时会自动加载该模块。
使用Twine进行安全打包与发布
推荐使用 twine 进行构建和上传,因其支持验证和加密传输:
pip install twine
生成源码分发包:
python setup.py sdist
上传至PyPI:
twine upload dist/*
首次上传前可先推送到测试仓库验证:
twine upload --repository-url https://test.pypi.org/legacy/ dist/*