Python模块打包及发布

概述:
如何将自己开发的库分享给别人使用,使用pip install安装。
本文章包含制作python安装包和发布。
并且,通过这个步骤,我可深入了解各个模块中的内容,方便自己使用别人的库

参考资料:
https://packaging.python.org/tutorials/packaging-projects/

1.创建setup.py文件

建立如下所示的文档结构

1
2
3
4
5
6
7
├── example_pkg # packet 文件
│   ├── __init__.py # 全局变量定义等,可以直接是空文件,定位
│   └── test_pkg.py
├── LICENSE # 许可证
├── README.md # 描述文件
├── setup.py # 配置文件
└── tests # 测试文件夹

其中setup.py文件里面需要设置packet的配置,里面有注释:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import setuptools

with open("README.md","r") as fh:
long_description = fh.read()

setuptools.setup(
name = "Emir-Liu-packet", #distribution name of package
version = "0.0.1",
author = "Emir-Liu",
author_email = "egliuym@gmail.com",
description = "my first test packet", # a short,one-sentence summary
long_description = long_description, # the long description is loaded from README.md
long_description_content_type = "text/markdown",
url = "https://emir-liu.github.io/", # URL of the homepage of the project
packages = setuptools.find_packages(), # a list of all python import packages that should be included in the destribution package
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
], # some additional metadata about package ,at least license ,operating system and verson of python
python_requires = '>=3.0',
)

2.打包文件

1
2
python3 -m pip install --user --upgrade setuptools wheel
python3 setup.py sdist bdist_wheel

注意打包文件里面不写程序是没有输出的,打包之后应该会有文件夹(dist中包含.whl和.tar.gz文件),之后上传这个文件夹

3.注册Pypi,然后上传

先注册pypi,邮箱激活

然后,在~/.pypirc中写入:

1
2
3
4
5
6
7
8
9
10
11
12
[distutils]
index-servers =
pypi
testpypi

[testpypi]
repository = https://test.pypi.org/legacy/

[pypi]
repository = https://upload.pypi.org/legacy/
username = xxx
password = xxx

这一步只要一开始弄好就不用输入密码什么的了。

上传:
twine upload dist/*

之后你可以在网站上看到你的包了。