Python file packaging and distribution method

Python file packaging and distribution method

The Python file packaging and publishing method is suitable for modularizing and distributing developed Python files. Can be installed in a local python environment.



Preface

I have three python files, A.py and B.py and C.py
Among them, A.py depends on importing B.py and C.py
Package these three files into modules to support subsequent users to directly import and use


1. Document organization

Create a directory (package directory) to store these three files. The directory structure is as follows:

my_module/
    __init__.py
    A.py
    B.py
    C.py
  1. Create an empty init.py file in the my_module directory. This file is used to instruct the Python interpreter to recognize the my_module directory as a package.

  2. Place the A.py, B.py and C.py files into the my_module directory respectively.

  3. Within the A.py file, B.py and C.py can be imported, just like in a regular Python script. For example:

# A.py
from . import B
from . import C

2. setuptools distribution operation

  1. Make sure the project directory structure is as follows:
parent_file/
    my_module/
        __init__.py
        A.py
        B.py
        C.py
    setup.py
  1. In the setup.py file, define project metadata and package information. A simple setup.py might look like this:
from setuptools import setup, find_packages

setup(
    name="my_module",
    version="0.1",
    packages=find_packages(),
)

In this example, name is the name of the package, version is the version of the package, and packages use find_packages() to automatically find and include Python packages.

  1. In the project root directory, use command line tools to go into the directory and run the following command to build a source distribution package (sdist):
python setup.py sdist
  1. At this time, the dist folder will be generated, enter this folder
pip install /path/to/my_module/dist/my_module-0.1.tar.gz

3. Precautions

When dealing with dependencies, the import methods of B.py and C.py are different in different situations.
During development, the import method is:

import B
import C

When distributed, it is:

from . import B
from . import C

Guess you like

Origin blog.csdn.net/qq_48081868/article/details/134067217