Create your own python package

python包结构

1
2
3
4
5
6
7
8
9
10
11
12
13
package folder -+
|
+setup.py <--主要的配置/安装文件,必须
|
+setup.cfg <--提供给用户的配置文件,可选
|
+README <--readme文件,可选
|
+MANIFEST.in <--打包配置文件模板,用来和setup.py一起生成打包配置文件MANIFEST,可选
|
+<your package> <--你的package,最好与package folder名字一致
|
+<other files> <--额外的文件

在pipy上注册一个账号

  • pipy注册一个账号,记得通过邮件认证

创建setup.py脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from setuptools import setup, find_packages
setup(
name = "HelloWorld",
version = "0.1",
packages = find_packages(),
scripts = ['say_hello.py'],

# Project uses reStructuredText, so ensure that the docutils get
# installed or upgraded on the target machine
install_requires = ['docutils>=0.3'],

package_data = {
# If any package contains *.txt or *.rst files, include them:
'': ['*.txt', '*.rst'],
# And include any *.msg files found in the 'hello' package, too:
'hello': ['*.msg'],
},

# metadata for upload to PyPI
author = "Me",
author_email = "me@example.com",
description = "This is an Example Package",
license = "PSF",
keywords = "hello world example examples",
url = "http://example.com/HelloWorld/", # project home page, if any

# could also include long_description, download_url, classifiers, etc.
)

编写MANIFEST.in文件

  • MANIFEST.in文件可以告诉setup.py在使用 sdist 命令制作安装包时, 要包含哪些文件。例如有时候我们需要包含版权文件, 有时我们的程序需要依赖一些数据文件。
  • 1
    2
    3
    4
    5
    6
    # 导入根目录下满足*.txt的文件
    include *.txt
    # 递归导入examples目录下满足*.txt和*.py的文件
    recursive-include examples *.txt *.py
    # 导入满足examples/sample?/build的文件夹下所有文件
    prune examples/sample?/build
  • 注意: 当根目录下存在MANIFEST.in文件时,Setuptools将不会再采用自动处理的设定,因此需要在MANIFEST.in文件中指明所有需要导入的文件。

打包并测试上传

  • $ python setup.py sdist
  • $ python setup.py sdist upload

通过pip安装自定义包

1
$ pip install HelloWorld

一些问题

  • 没有编写MANIFEST.in文件导致通过pip安装之后加载不出相应的文件报错
  • 包内调用包中模块的时候应当采用

    1
    from . import xxx`

    的格式,在本地测试的时候会报错,只需要把相关的sys.path添加进去即可,通过sys.path.append()(Mac)

  • 祝早日成为python贡献者之一