如何造自己的轮子(python发布自己的第三方库, 让PyPI中存在自己的项目)?

本文指导你如何创建并发布自己的Python库,通过setup.py文件配置,遵循pipinstall的规则,并在PyPI上注册。学习如何编写setup.py,使之既能被pip识别又能导入,完成从新手到数据科学家的轮子制造之旅。

当你的项目走到这一步,是及其令人兴奋和激动的时刻;那么,在这里将告诉你如何走完最后一步。
(还记得那句不要重复造轮子吗?这里你可是在发明轮子啊!)
记得刚开始使用python,使用pip install numpy时,感觉那些写numpy的数据科学家实在是太厉害了,什么时候也能写一个自己的xxx库,然后:pip install xxx;那会是多么激动的事啊。下面就会实现这个理想。
步骤:

  1. 在你的项目的根目录下新建setup.py文件;其实项目的目录和setup.py的位置是很有讲究的。和setup.py同级目录的那些包等是在发布后可以pip install xxx的,但是父级目录不可以。比如:
    MyProject
        |—package1
        |    |
        |    |—file1.py
        |—package2
        |    |
        |    |—file2.py
    setup.py
    这种目录,在发布后 可以使用 pip install HHH 安装;注意:HHH是在setup.py中指定的库名,你可以理解为他和项目之间是一种映射关系。
    当你安装完HHH,你用pip list缺失可以看到HHH这个库,但是你不能import HHH; 你只能import package1,或者 import package2 ,或者from package1.file1 import XXX;
    所以,你要像numpy那样pip list能看见,也能 import 导入;那么你的setup.py应该和项目名处于同一级目录。
  2. 在https://pypi.org/官网注册自己的账户;发布的时候要用到;
  3. setup.py的文件内容:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Note: To use the 'upload' functionality of this file, you must:
#   $ pipenv install twine --dev

import io
import os
import sys
from shutil import rmtree

from setuptools import find_packages, setup, Command

# Package meta-data.  1》》》
# 写入自己的内容 start——1
NAME = 'OBC2AI'   # 为项目取名,这个名字就是 pip install xxx的xxx
DESCRIPTION = 'AI Head'
URL = 'https://github.com/IamJiangBo/OBC_AI'
EMAIL = 'chencl9@asiainfo.com'
AUTHOR = 'Charlene'
REQUIRES_PYTHON = '>=3.6.13'
VERSION = '0.1'   # 为项目指定目前的版本号
# end——1
with open('README.md', 'r', encoding='utf-8') as fh:
    long_description = fh.read()

# What packages are required for this module to be executed?
REQUIRED = [
    # 'requests', 'maya', 'records',
]

# What packages are optional?
EXTRAS = {
    # 'fancy feature': ['django'],
}

# The rest you shouldn't have to touch too much :)
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!

here = os.path.abspath(os.path.dirname(__file__))

# Import the README and use it as the long-description.
# Note: this will only work if 'README.md' is present in your MANIFEST.in.in file!
try:
    with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
        long_description = '\n' + f.read()
except FileNotFoundError:
    long_description = DESCRIPTION

# Load the package's __version__.py module as a dictionary.
about = {}
if not VERSION:
    project_slug = NAME.lower().replace("-", "_").replace(" ", "_")
    with open(os.path.join(here, project_slug, '__version__.py')) as f:
        exec(f.read(), about)
else:
    about['__version__'] = VERSION


class UploadCommand(Command):
    """Support setup.py upload."""

    description = 'Build and publish the package.'
    user_options = []

    @staticmethod
    def status(s):
        """Prints things in bold."""
        print('\033[1m{0}\033[0m'.format(s))

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        try:
            self.status('Removing previous builds…')
            rmtree(os.path.join(here, 'dist'))
        except OSError:
            pass

        self.status('Building Source and Wheel (universal) distribution…')
        os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))

        self.status('Uploading the package to PyPI via Twine…')
        os.system('twine upload dist/*')

        self.status('Pushing git tags…')
        os.system('git tag v{0}'.format(about['__version__']))
        os.system('git push --tags')

        sys.exit()

# 写入自己的内容 start——2
# Where the magic happens:
setup(
    name="OBC2AI",   # 和前边的保持一致
    version=about['__version__'],
    description="AI Head",
    long_description=open('README.md', 'r', encoding='utf-8').read(),   # 默认是readme文件。
    long_description_content_type='text/markdown',
    author="Charlene",
    author_email="chencl9@asiainfo.com",
    python_requires=">=3.6.13",
    url="https://github.com/IamJiangBo/OBC_AI",
    packages=find_packages(exclude=["tests", "*.tests", "*.tests.*", "tests.*"]),
	
	# end——2
    # If your package is a single module, use this instead of 'packages':
    # py_modules=['mypackage'],

    # entry_points={
    #     'console_scripts': ['mycli=mymodule:cli'],
    # },
    # REQUIRED 是项目依赖的库
    install_requires=[],
    extras_require=EXTRAS,
    include_package_data=True,
    license='MIT',
    classifiers=[
        # Trove classifiers
        # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy'
    ],
    # $ setup.py publish support.
    cmdclass={
        'upload': UploadCommand,
    },
)

需要自己写的地方用 start—i 和 end—i 包含着了。
4.在setup.py所在的目录下执行 python setup.py upload即可完成发布。

注意:如果只是在本地安装。使用命令:python setup.py bdist_wheel
生成的轮子文件在项目根目录下的dist目录中。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值