学习过程中参考网站https://packaging.python.org/tutorials/packaging-projects/,主要是翻译成中文。
- 在本地建立项目的时候,首先需要创建如下的文件结构:
packaging_tutorial/
example_pkg/
__init__.py
接下来所有的操作都是在packaging_tutorial文件夹下面
- 创建打包的文件
packaging_tutorial/
example_pkg/
__init__.py
setup.py
LICENSE
README.md
- setup.py
该文件的作用是setuptools的build script.他传递给setuptools关于你的包的名字,版本等信息等。
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="example-pkg-YOUR-USERNAME-HERE", # Replace with your own username
version="0.0.1",
author="Example Author",
author_email="[email protected]",
description="A small example package",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/pypa/sampleproject",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
)
- README.md
# Example Package
This is a simple example package. You can use
[Github-flavored Markdown](https://guides.github.com/features/mastering-markdown/)
to write your content.
LICENSE
https://choosealicense.com/-
生成distribution archives
这样的话就可以使用pip进行安装了;- 确保自己有最新的setuptools和wheel安装:
python3 -m pip install --user --upgrade setuptools wheel
- 在setup.py所在的文件夹运行如下代码:
python3 setup.py sdist bdist_wheel
最终应该输出一些文字,一旦成功在dist文件夹会生成两个文件:
dist/
example_pkg_YOUR_USERNAME_HERE-0.0.1-py3-none-any.whl
example_pkg_YOUR_USERNAME_HERE-0.0.1.tar.gz
- 上传distribution archives:
注册Test PyPI 账户https://test.pypi.org/account/register/; 获得PyPI API token 之后便可以安全的上传project;
在https://test.pypi.org/manage/account/#api-tokens生成新的API token;在你保存和复制token之前都不要提前关闭页面;
注册完毕
python3 -m pip install --user --upgrade twine
- 一旦安装完毕,可以使用一下代码上传所有的在dist的archives:
python3 -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*
- username: token
password: pypi- prefix
最终可以看到类似的内容:
Uploading distributions to https://test.pypi.org/legacy/
Enter your username: [your username]
Enter your password:
Uploading example_pkg_YOUR_USERNAME_HERE-0.0.1-py3-none-any.whl
100%|█████████████████████| 4.65k/4.65k [00:01<00:00, 2.88kB/s]
Uploading example_pkg_YOUR_USERNAME_HERE-0.0.1.tar.gz
100%|█████████████████████| 4.25k/4.25k [00:01<00:00, 3.05kB/s]
- 可以再网页上看到自己的package:https://test.pypi.org/project/example-pkg-YOUR-USERNAME-HERE