首先说明,这种方式目前是一种「非主流」的方式,是在安装IPython最新版本时无意发现的。

我们先看一个真实的项目entrypoints,我们先安装它:

1
2
3
❯ virtualenv venv -p /usr/local/bin/python3 # flit依赖Python 3,但是可以分发Python 2的包
❯ source venv/bin/activate
❯ pip install entrypoints

这看起来一直很正常。我们再看看项目文件结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
❯ tree -L 2
.
├── LICENSE
├── doc
│   ├── Makefile
│   ├── api.rst
│   ├── conf.py
│   └── index.rst
├── entrypoints.py
├── flit.ini
└── tests
├── __init__.py
├── samples
└── test_entrypoints.py

有没有发现,没有setup.py文件! 这和我们平时对打包上传的理解有冲突呀。

这是怎么实现的呢?首先我们先了解下下面2个PEP:

  1. PEP 516 – Build system abstraction for pip/conda etc
  2. PEP 517 – A build-system independent format for source trees

对, 就是让flit.ini替代(部分)了setup.py的作用:

1
2
3
4
5
6
7
8
9
❯ cat flit.ini
[metadata]
module = entrypoints
author = Thomas Kluyver
author-email = thomas@kluyver.me.uk
home-page = https://github.com/takluyver/entrypoints
classifiers = License :: OSI Approved :: MIT License
requires-python = >=2.7
requires = configparser (>=3.5); python_version == '2.7'

我们来体会下使用flit的用法,首先安装它:

1
❯ pip install flit

现在我们创建一个简单的项目,就叫「flit_test」吧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
❯ mkdir flit_test
❯ cd flit_test
❯ flit init # 初始化
Module name: flit_test
Author: Dongweiming
Author email: ciici123@gmail.com
Home page: http://www.dongwm.com
Choose a license (see http://choosealicense.com/ for more info)
1. MIT - simple and permissive
2. Apache - explicitly grants patent rights
3. GPL - ensures that code based on this is shared with the same terms
4. Skip - choose a license later
Enter 1-4: 1
Written flit.ini; edit that file to add optional extra info.

接着我们创建初始化填写的模块文件:

1
2
3
4
5
6
❯ cat flit_test.py
'''Some docstring'''
__version__ = '0.1'
def main():
print('Hello World')

我们现在给flit.ini文件添加一个入口:

1
2
[scripts]
hello=flit_test:main

这样在安装之后就可以在命令行直接使用hello命令,会执行打印’Hello World’。

最后一步就是上传到PYPI了:

1
2
3
4
5
❯ flit wheel --upload
...
Registered flit_test with PyPI I-flit.upload
Uploading dist/flit_test-0.1-py2.py3-none-any.whl... I-flit.upload
Package is at https://pypi.python.org/pypi/flit_test I-flit.upload

我们现在验证下flit_test这个包:

1
2
3
4
5
❯ pip install flit_test
❯ hello
Hello World
❯ which hello
/Users/dongweiming/entrypoints/venv/bin/hello