Practical tutorial: How to publish your own Python package on PyPI

1. Purpose of PyPi

We often use third-party packages in Python. By default, the third-party tool packages used are basically downloaded from Pypi.org.

Let’s give an example: If you want to use Python to implement a financial quantitative analysis tool, the currently more useful sources of financial data are Yahoo and Google. You may need to read the APIs of these two platforms, and then implement the code for downloading and analyzing data in sequence. Isn't it troublesome? So you can go to PyPi to find out if this content has been written. Fortunately, you found it. You found a package called yfinance.

https://github.com/ranaroussi/yfinance

At this time, you only need one command, which saves us the trouble of implementing it from scratch:

pip install yfinance

That’s it. Isn’t it very convenient?

Technology Exchange

Technology must be shared and communicated, and it is not recommended to work behind closed doors. One person can go very fast, and a group of people can go further.

This article is shared and recommended by fans. Information, information sharing, data, and technical exchange improvements can all be obtained by joining the communication group. The group has more than 2,000 members. The best way to add comments is: source + direction of interest, which is convenient Find like-minded friends.

Method ①, add WeChat account: pythoner666, remarks: from CSDN + add group
Method ②, search public account on WeChat: Python learning and data mining, background reply: add group

picturePyPIIt is the abbreviation of Python Package Index, which actually represents Python's Packag index, which is also the official index of Python.

You need to install pip in the local environment first, and then use the command if you want to install other tool packages:

pip install <package name>

Official address:https://pypi.org/

One sentence explanation: If you are using a Java project, you can just understand PyPi as Maven.

So how do we upload a package we developed to PyPI for other people to use.

2. Python package publishing steps

Let’s start with how to publish your Python project to PyPI

2.1 Create directory structure

Create a test project, for example project_demo, under this project, create a package directory to be released, for example: , package_mikezhou_talkand in this project_demodirectory, create: setup.py, LICENSE, README.rstseveral files in sequence. At this time, the directory structure is:

➜  project_demo tree -L 2
.
├── LICENSE
├── README.rst
├── package_mikezhou_talk
│   └── __init__.py
└── setup.py

1 directory, 4 files

2.2 Preparing documents

Next we will write the files except the code one by one.

1. README.rst is a description file about the project, which generally includes how to install the project, how to use the project, etc. Markdown syntax can be referred tohttps://rest-sphinx-memo.readthedocs.io/en/latest/ReST.html

Open README.rst and enter the following content. You can customize this item to include some introduction to the project.

# Example Package
This is a simple example package. You can use
to write your content.

2. LICENSE.txt, create a license

It is important that every package uploaded to the Python Package Index includes a license. This tells users who install your package the terms under which your package can be used. Open source license, such as MIT, Apache license 2.0, etc. For help selecting a license, visit https://choosealicense.com/. After selecting a license, open LICENSE and enter the license text.picture

3. setup.py file

setup.py is the build script of setuptools, which is used to describe the project. This file will be used during packaging. It tells PyPI what our project is called, what version it is, which libraries it depends on, which operating systems it supports, which versions of Python it can run on, and so on.

Standard script example:

from distutils.core import setup
from setuptools import find_packages

with open("README.rst", "r") as f:
  long_description = f.read()

setup(name='package_mikezhou_talk',  # 包名
      version='1.0.0',  # 版本号
      description='A small example package',
      long_description=long_description,
      author='mike_talk',
      author_email='[email protected]',
      url='',
      install_requires=[],
      license='BSD License',
      packages=find_packages(),
      platforms=["all"],
      classifiers=[
          'Intended Audience :: Developers',
          'Operating System :: OS Independent',
          'Natural Language :: Chinese (Simplified)',
          'Programming Language :: Python',
          'Programming Language :: Python :: 2',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3',
          'Programming Language :: Python :: 3.5',
          'Programming Language :: Python :: 3.6',
          'Programming Language :: Python :: 3.7',
          'Programming Language :: Python :: 3.8',
          'Topic :: Software Development :: Libraries'
      ],
      )

Important parameter description:

  • name: The name of the project, name is the distribution name of the package.

  • version: The version of the project. It should be noted that only one version is allowed to exist on PyPI. If there are any subsequent changes to the code, the version number needs to be increased when uploading again.

  • author and author_email: The name and email of the project author, used to identify the author of the package.

  • description: a short description of the project

  • long_description: A detailed description of the project, which will be displayed on the PyPI project description page. Must be in rst(reStructuredText) format

  • packages: Specify the packages to be included in the final published package.

  • install_requires: Which libraries the project depends on, these libraries will be automatically installed during pip install

  • classifiers: Other information, generally including the Python version supported by the project, License, and supported operating systems.

Clone the setup.py repository (recommended)

If you feel that handwriting setup.pyscript files is too difficult, I recommend another easy method for you.

Kennethreitz, the author of the famous requests library, has prepared a warehouse for everyone as a good template for setup.py. Of course, you can also handwrite setup.py yourself.

git clone  https://github.com/kennethreitz/setup.py

It is recommended that you directly edit the setup.py in the previous warehouse and only need to modify some necessary configurations.

2.3 Writing core code

Next we can write our own code. Please note that package_mikezhou_talkthe name of the source code folder (package directory in the warehouse) must be consistent with the package name (Name) configured in setup.py.

This content can be implemented by yourself according to your own needs. For example: I package_mikezhou_talkcreated a new main.py file in the sample package directory, and implemented the functions to be implemented in this file.

Example:

import itertools

case_list = ['用户名', '密码']
value_list = ['正确', '不正确', '特殊符号', '超过最大长度']


def gen_case(item=case_list, value=value_list):
    '''输出笛卡尔用例集合'''
    for i in itertools.product(item, value):
        print('输入'.join(i))

def test_print():
     print("欢迎搜索关注公众号: 「测试开发技术」!")

if __name__ == '__main__':
    test_print()

2.4 Generate distribution files

The next step is to generate a distribution package for the package. These are archives uploaded to the package index and can be installed via pip.

Make sure you have setuptools and wheel the latest version installed:

python3 -m pip install --user --upgrade setuptools wheel

Before generating this, you can run python setup.py checkand check if there are any errors in setup.py. If no errors are reported, the next output is usually running check.

1. After preparing the above steps, a package will be basically complete. The rest is packaging. You can use the following command to package a source code package:

python setup.py sdist build

In this way, there will be an additional package ending with tar.gz in the dist folder of the current directory:

2. You can also package a package in wheels format by using the following command:

python setup.py bdist_wheel --universal

This will generate a whl file under the dist folder.

3. Or run this command from the same directory where setup.py is located:

python3 setup.py sdist bdist_wheel

The above command will generate a tar.gz source code package and a .whl Wheel package in the dist directory.

2.5 Publishing packages to PyPi

1. The next step is to https://pypi.org/account/register/register an account. If you have an account, please ignore it. Remember your account and password, which will be used when uploading packages later.

2. The next step is to upload your package. Here, use twine to upload it. You need to install twine first (use twine to upload the distribution package, and only twine> = 1.11.0 can correctly send metadata to Pypi)

pip install twine

3. After installation, run the following commands to upload the library and package. During this process, you will be asked to enter your registered username and password.

twine upload dist/*

Enter the username and password registered with PyPI. Once the command completes, you should see output similar to this:

➜  twine upload dist/*
Uploading distributions to https://upload.pypi.org/legacy/
Enter your username: mikezhou_talk
Enter your password:
Uploading package_mikezhou_talk-1.0.0-py3-none-any.whl
100%|██████████████████████████████████████| 7.84k/7.84k [00:03<00:00, 2.29kB/s]
Uploading package_mikezhou_talk-1.0.0.tar.gz
100%|██████████████████████████████████████| 6.64k/6.64k [00:01<00:00, 6.05kB/s]

View at:
https://pypi.org/project/package-mikezhou-talk/1.0.0/

After the upload is completed, our project was successfully published to PyPI.

3. Verify that the release of PYPI is successful

After the upload is completed, success will be displayed, and we can view it directly on PyPI, as follows:

pictureYou can use pip to install the package and verify that it works. Create a new virtualenv (see Installing Packages for detailed instructions) and install the package from TestPyPI:

python3 -m pip install --index-url https://test.pypi.org/simple/ package-mikezhou-talk
或
pip install package-mikezhou-talk -i https://www.pypi.org/simple/

As shown below:picture

Enter the Python Shell to verify the results as follows:
Insert image description here

At this point, we have successfully published the Python program we developed to PyPI. At this time, you can directly install package-mikezhou-talkthe package in the example through the pip command in your local environment.

Official website address:

https://pypi.org/project/package-mikezhou-talk/1.0.0/

Guess you like

Origin blog.csdn.net/m0_59596937/article/details/132797213