Small knowledge, big challenge! This article is participating in the “Essentials for Programmers” creative activity. This article has participated in the “Digitalstar Project” to win a creative gift package and challenge the creative incentive money.

The 10th official Python column, stop! Don’t miss this zero-based article!

How to develop a Python library and import it to run, basically complete a preliminary library

Here’s how to make the library a command line tool so that others can use it by typing commands just like we do with Python or PIP tools!

Readers can join the exchange by checking the committee’s homepage or going to GitHub to give a Star.

Prepare the Python library as a command line

The project structure is as follows, and the first step is to have it support the command line.

Remember that there was a setup.py file in the previous project screenshots.

Setup.py organizes the entire project module code and basic information, and contains the tricks to support the command line.

Let’s take a look at the code and focus on a familiar one: entry_points.

# -*- coding: utf-8 -*-
# @csDN /Juejin/Wechat: Lei Xuewei
# @XueWeiTag: OpenSource
# @File : setup.py
# @Project : pypi_seed


from distutils.core import setup
from setuptools import find_packages

setup(name='pypi_seed'.# the package name
      version='1.0.3'.# version number
      keywords=("pypi_seed"."seed"."generator"."levin"."leixuewei"),
      description='A small tool to demo on upload package to pypi and utility scripts to generate a pypi seed',
      long_description="""A small tool to demo on upload package to pypi and utility scripts to generate a pypi seed! Powered by py4ever team!" "",
      author='levin',
      author_email='[email protected]'.# Project contact
      url='https://github.com/py4ever/pypi_seed'.The committee has deleted some information that is not the focus of this article
      entry_points={
          'console_scripts': [
              'pypiseed = pypi_seed.main:main'.'pyseed = pypi_seed.main:main'
          ]
      },
      classifiers=[
          'Intended Audience :: Developers' Pypi_seed setup.py has been deleted from github or Gitee to support multiple versions],)Copy the code

Explain setup.py

To put it simply, setup.py is like a map of an open source module.

It includes author information, project description, version, project links, and most importantly, “entry_points” on the command line after installation.

With entry_points set, when we install the module using the PIP tool, it will automatically create the corresponding files for us.

For example, entry_points above are two command tools:

  • Pypiseed is a command line tool. Peer to pypi_seed. Main :main
  • Pyseed is a command-line tool, equivalent to calling pypi_seed. Main :main

Setup. py Description of other parameters

Focus on the author, project name, contact information, sorted and explained below:

  • Name: Project name, very important! Other developers use this to search your library
  • Author: the author
  • Keywords: project keywords
  • Description: Project description
  • Author_email: indicates the author’s email address
  • Url: Project home page

These are fairly straightforward, written with the open source tools in mind.

If it does not fit, place it in the long Description field. In case the user has any feedback while using the project, they can also contact email, or continue to interact through the project home page, which can keep the project constantly improved and updated with The Times!

The second step is to develop a Python program for command-line processing

We have a portal. We can go through

Pyseed parameters# pypi_seed is called
Copy the code

Ok, with entry_points, it calls pypi_seed. Main :main. The committee has helped you look at the source code.

Pypiseed/Pyseed calls the show_help and args2dict methods of an application.

Open source project source code parsing

Here is the show_help method, which focuses on printing out some usage information and a brief description of the project.

def show_help() :
    print('usage:')
    print('-h, --help: print help message.')
    print('-p, --project: your desired project name')
    print('-P, --path: where to save the sample project after code-generation')
    print('-a, --author: the author information')
    print("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =")
    show_sample_run()
    show_about()
Copy the code

This is the core of this article, parsing user input.

In order to facilitate the analysis, the committee only extracted the core code section, let’s have a look.

import sys
import getopt

def args2dict():
    argv = sys.argv[1:]
    if '-h' in argv or '--help' in argv:
        show_help()
        exit(0)
    try:
        opts, args = getopt.getopt(argv, "p:P:a"["path="."author="."project="])
    except Exception as e:
        raise ValueError("Looks like missing value, please check usage by '-h'. Current error : %s " % str(e))
    project = author = path = None
    for opt, arg in opts:
        if opt in ['-p'.'--project']:
            project = arg
        elif opt in ['-a'.'--author']:
            author = arg
        elif opt in ['-P'.'--path']:
            path = arg
    if project is None:
        print("please input project with '-p' or '--project', e.g. -p my_project ")
        raise ValueError("Missing project")
    if author is None:
        print("please input author with '-a' or '--author', e.g. -a whoami ")
        raise ValueError("Missing author")
    if path is None:
        path = os.getcwd()
        print("path is not given, so will use default as current directory : %s" % path)
    return dict(project=project, author=author, path=path)
Copy the code

Core code explanation

There are three main steps here

  • Obtain terminal parameters and determine whether to output help
  • Parse p: p: a parameters (-a, -p, -p) into a dict using the getopt library (manage project/author/path, etc.)
  • Returns the dictionary to the generator call to generate the seed item.

Finally use the command line to call your library:

Install your library:

pip install pypi_seed
Copy the code

Use the following command:

pyseed -p demo_proj -a testuser -P '. '
Copy the code

Here’s what it looks like. It’s a simple project, and with a little bit of development you can make it your own module and share it.

conclusion

It is not easy for others to find your library, and the use of the command line must be concise and easy to understand. Be sure to make the help prompt friendly and convenient to use quickly.

  1. Learn to use setup.py to efficiently organize project code and configuration.
  2. Developing command-line tools focuses on processing user input parameters.
  3. A good open source project needs to provide easy access to help.

Complete open source project code here: Pypi-Seed on Github

If you like Python, please pay attention to learn the Basic Python column or Get started in Python to master the big column

Continuous learning and continuous development, I am Lei Xuewei! Programming is fun. The key is to get the technology right. Creation is not easy, please pay attention to the collection of likes, or leave a comment to encourage!

Reference links:

Packaging.python.org/tutorials/p…