python打包pip

我这里是自用的,打包直接安装了,方便多个地方引用,不需要写一堆路径

最简打包

比如 - 你的打包的pip库名字是 pytest - 你封装的函数只有一个

1
2
3
4
import numpy as np
def fun(str):
print(str + ": ok")
print(np.pi)

你需要的工作

  • 创建最外层文件夹,名字随意 比如 test

  • test 文件夹里创建 pytest 文件夹 > 也就是你打包的pip库名字

  • pytest 文件夹里创建的函数文件 __init__.py > 注意函数可以写在这里,也可以其他地方,但是这个文件必须有 __init__.py 里面的内容

    1
    2
    3
    4
    5
    6
    import numpy as np


    def fun(str):
    print(str + ": ok")
    print(np.pi)

  • test 文件夹里创建 setup.py 文件

    里面的内容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import setuptools

    setuptools.setup(
    name='pytest',
    # 版本号
    version='1.0',
    author="你的名字",
    author_email="test@gmail.com",
    # 你的打包的pip库名字
    py_modules=["pytest"],
    # 你的依赖
    install_requires=["numpy"],
    # 自动打包文件
    packages=setuptools.find_packages(),
    description="库的说明")

最后你的文件目录应该是

1
2
3
4
test
├── pytest
│ └── __init__.py
└── setup.py

最后安装,在 test 文件夹里执行

1
pip install ./

安装位置,以linux为例:~/.local/lib/python3.10/site-packages/pytest/

如果前面没有错误,不会报错,安装成功

在其他文件里可以引用刚才的函数

1
2
3
4
5
6
7
import pytest


pytest.fun("a")

# a: ok
# 3.141592653589793

复杂

  • 如果你需要写一些比较多的说明

    在刚才的 test 文件夹里新建 README.md

    然后修改 setup.py

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    import setuptools


    with open("README.md", "r") as fh:
    long_description = fh.read()

    setuptools.setup(
    name='pytest',
    # 版本号
    version='1.0',
    author="你的名字",
    author_email="test@gmail.com",
    # 你的打包的pip库名字
    py_modules=["pytest"],
    # 你的依赖
    install_requires=["numpy"],
    # 自动打包文件
    packages=setuptools.find_packages(),
    description="库的说明",
    long_description=long_description,
    long_description_content_type="text/markdown")

  • 可能的需要封装的函数库比较复杂

    比如有多个文件之间相互引用

    a.py

    1
    2
    3
    4
    import numpy as np

    def get_a():
    return np.pi * 3

    b.py 需要引用 a.py 中的函数,正常导入包你的这个包就可以,也就是自己引用自己

    1
    2
    3
    4
    import numpy as np
    import pytest

    print(pytest.get_a())
  • 可能你有多个文件夹

    每一个文件夹里,必须有 __init__.py 这个文件,即使这个文件空白

  • 可能你有一些常量放在了 data.json 文件里

    首先在刚才的 setuptools.setup( 里添加 include_package_data=True,

    然后,在刚才的 test 文件夹里新建 MANIFEST.in

    里面的内容

    1
    include data.json

    引用它,建议在 pytest 文件夹的 __init__.py 里写

    1
    2
    3
    import os

    this_dir, this_filename = os.path.split(__file__)

    其他地方引用它

    1
    2
    3
    import pytest

    file = pytest.this_dir + "/data.json"

本文作者:yuhldr
本文地址https://yuhldr.github.io/posts/4e0c9d8f.html
版权声明:转载请注明出处!