本文假设你在 GitHub 上已经有一个想要打包和发布的项目。
第 0 步:获取项目许可证
在做其他事之前,由于你的项目要开源,因此应该有一个许可证。获取哪种许可证取决于项目包的使用方式。开源项目中一些常见许可证有 MIT 或 BSD。
要在项目中添加许可证,只需参照以下链接中的步骤,将 LICENSE 文件添加到项目库中的根目录即可: https://help.github.com/en/articles/adding-a-license-to-a-repository
第 1 步:让你的代码准备就绪
要将项目进行打包,你需要做一些预备工作:
- 让你的项目结构正确就位。通常情况下,项目库的根目录包含一个以项目名称命名的文件夹,项目的核心代码应该位于此文件夹中。在这个文件夹之外是运行和构建包(测试、文档等)所需的其他代码。
- 核心文件夹应包括一个(或多个)模块和一个 __init__.py 文件,该文件包含你希望让终端用户访问的类/函数。此文件还可以包含包的版本,以便于终端用户访问。
- 理想情况下,应使用 logging 包来设置合理的日志记录系统(而不是用 prints 输出)。
- 理想情况下,应将你的核心代码分配到一个或多个类中。
from .estimate import Estimator
以__init__.py 为例,如果 Estimator 是终端用户将会访问的类(该类在 estimate.py 文件中定义)
import logging class LogMixin(object): @property def logger(self): name = '.'.join([self.__module__, self.__class__.__name__]) FORMAT = '%(name)s:%(levelname)s:%(message)s' logging.basicConfig(format=FORMAT, level=logging.DEBUG) logger = logging.getLogger(name) return logger
以日志系统为例:LogMixin 类可以在其他任何类中使用
第 2 步:使用打包工具创建 setup.py
在你的项目有了一套结构之后,你应该在项目库的根目录下添加 setup.py 文件。这有助于所有发布和版本维护过程的自动化。以下是 setup.py 的例子(源代码:https://github.com/nathan-toubiana/scitime/blob/master/setup.py)。
from setuptools import setup from os import path DIR = path.dirname(path.abspath(__file__)) INSTALL_PACKAGES = open(path.join(DIR, 'requirements.txt')).read().splitlines() with open(path.join(DIR, 'README.md')) as f: README = f.read() setup( name='scitime', packages=['scitime'], description="Training time estimator for scikit-learn alg<p style="color:transparent">本文来源gao!%daima.com搞$代*!码$网3</p>orithms", long_description=README, long_description_content_type='text/markdown', install_requires=INSTALL_PACKAGES, version='0.0.2', url='http://github.com/nathan-toubiana/scitime', author='Gabriel Lerner & Nathan Toubiana', author_email='[email protected]', keywords=['machine-learning', 'scikit-learn', 'training-time'], tests_require=[ 'pytest', 'pytest-cov', 'pytest-sugar' ], package_data={ # include json and pkl files '': ['*.json', 'models/*.pkl', 'models/*.json'], }, include_package_data=True, python_requires='>=3' )
setup.py 文件的示例
几点注意事项:
- 如果你的包有依赖项,处理这些依赖项的简单方法是在配置文件中通过 install_requires 参数来添加依赖项(如果列表很长,你可以像之前那样指向一个 requirement.txt 文件)。
- 如果你希望在任何人安装包时(从项目库中)下载元数据,则应通过 package_data 参数来添加这些元数据。
- 有关 setup() 函数的更多信息,请参见:https://setuptools.readthedocs.io/en/latest/setuptools.html