软硬件环境

  • ubuntu 18.04 64bit
  • anaconda with python 3.6
  • setup.py

前言

科技发展到今日,软件开发已经变得越来越复杂,再也不是单单靠一个人的力量就能够完成,在这种背景下,工程化就变得越来越重要,一方面它可以帮助我们规范我们的工程,这里的规范不仅仅是指代码的规范,还有文档,测试等;另一方面也方便了后来者的阅读理解,节省时间及人力成本,比如团队中新员工的加入,或者项目开发者的离职交接,相信在国内的大环境下,这种情况不在少数。

最近在做一个基于人脸识别的考勤系统,本文就在这个项目的基础上,给大家讲讲 python 项目基于 setup.py 的打包及部署。首先给出项目的工程目录结构

python 项目中的sqlach python 项目中的setup.py_python 项目中的sqlach



项目本身是一个服务,运行环境是在服务器,因此我需要将它做成一个命令行工具。

setup.py文件简介

玩过 python 的应该都知道这个 setup.py 文件吧,特别是在开源领域。setuptools 是一个优秀的、可靠的 python 包安装与分发工具,而打包分发的关键在于编写 setup.py 文件。setup.py 文件编写的规则是从setuptools 导入 setup 及其它一些 辅助 模块函数, 并传入各类参数进行调用。

setup.py的使用

setup.py编写好了,接下来就是如何使用它了。setup.py 支持的命令非常多,可以调用 python setup.py --help-commands 进行查看

1Standard commands:
 2  build             build everything needed to install
 3  build_py          "build" pure Python modules (copy to build directory)
 4  build_ext         build C/C++ and Cython extensions (compile/link to build directory)
 5  build_clib        build C/C++ libraries used by Python extensions
 6  build_scripts     "build" scripts (copy and fixup #! line)
 7  clean             clean up temporary files from 'build' command
 8  install           install everything from build directory
 9  install_lib       install all Python modules (extensions and pure Python)
10  install_headers   install C/C++ header files
11  install_scripts   install scripts (Python or otherwise)
12  install_data      install data files
13  sdist             create a source distribution (tarball, zip file, etc.)
14  register          register the distribution with the Python package index
15  bdist             create a built (binary) distribution
16  bdist_dumb        create a "dumb" built distribution
17  bdist_rpm         create an RPM distribution
18  bdist_wininst     create an executable installer for MS Windows
19  check             perform some checks on the package
20  upload            upload binary package to PyPI
21
22Extra commands:
23  bdist_wheel       create a wheel distribution
24  build_sphinx      Build Sphinx documentation
25  alias             define a shortcut to invoke one or more commands
26  bdist_egg         create an "egg" distribution
27  develop           install package in 'development mode'
28  easy_install      Find/get/install Python packages
29  egg_info          create a distribution's .egg-info directory
30  install_egg_info  Install an .egg-info directory for the package
31  rotate            delete older distributions, keeping N newest files
32  saveopts          save supplied options to setup.cfg or other config file
33  setopt            set an option in setup.cfg or another config file
34  test              run unit tests after in-place build
35  upload_docs       Upload documentation to PyPI
36  nosetests         Run unit tests using nosetests
37  isort             Run isort on modules registered in setuptools
38  compile_catalog   compile message catalogs to binary MO files
39  extract_messages  extract localizable strings from the project code
40  init_catalog      create a new catalog based on a POT file
41  update_catalog    update message catalogs from a POT file
42

平常我们使用较多的有源码打包和本地安装

1python setup.py sdist

python 项目中的sqlach python 项目中的setup.py_git_02



1python setup.py install

python 项目中的sqlach python 项目中的setup.py_python 项目中的sqlach_03



setup.py的编写

还是以人脸识别这个项目为例

1# -*- coding: utf-8 -*-
 2# @time    : 18-8-10 下午8:28
 3# @author  : xugaoxiang
 4# @email   : djstava@gmail.com
 5# @website : https://xugaoxiang.com
 6# @file    : setup.py.py
 7# @software: PyCharm
 8
 9# Always prefer setuptools over distutils,导入模块
10from setuptools import setup, find_packages
11from os import path
12
13# 分别读取README.md和requirements.txt的内容
14here = path.abspath(path.dirname(__file__))
15
16# Get the long description from the README file
17with open('README.md', encoding='utf-8') as fp:
18    long_description = fp.read()
19
20with open('requirements.txt', encoding='utf-8') as fp:
21    install_requires = fp.read()
22
23setup(
24    # 名称
25    name='FacialAttendanceRecord',
26
27    # 版本号
28    version='1.0.1',
29
30    # 基本描述
31    description='Facial Attendance Record',
32
33    # 项目的详细介绍,我这填充的是README.md的内容
34    long_description=long_description,
35
36    # README的格式,支持markdown,应该算是标准了
37    long_description_content_type='text/markdown',
38
39    # 项目的地址
40    url='https://xugaoxiang.com',
41
42    # 项目的作者
43    author='xugaoxiang',
44
45    # 作者的邮箱地址
46    author_email='djstava@gmail.com',
47
48    # Classifiers,
49    classifiers=[  # Optional
50        # How mature is this project? Common values are
51        #   3 - Alpha
52        #   4 - Beta
53        #   5 - Production/Stable
54        'Development Status :: 3 - Beta',
55
56        # Indicate who your project is intended for
57        'Intended Audience :: Developers',
58        'Topic :: Software Development :: Build Tools',
59
60        # Pick your license as you wish
61        'License :: OSI Approved :: GNU GPL v3 License',
62
63        # Specify the Python versions you support here. In particular, ensure
64        # that you indicate whether you support Python 2, Python 3 or both.
65        'Programming Language :: Python :: 3',
66        'Programming Language :: Python :: 3.4',
67        'Programming Language :: Python :: 3.5',
68        'Programming Language :: Python :: 3.6',
69    ],
70
71    # 项目的关键字
72    keywords='facial attendance record',
73
74    # 打包时需要加入的模块,调用find_packages方法实现,简单方便
75    packages=find_packages(exclude=['contrib', 'docs', 'tests', 'build', 'dist']),
76
77    # 项目的依赖库,读取的requirements.txt内容
78    install_requires=install_requires,
79
80    # 数据文件都写在了MANIFEST.in文件中
81    include_package_data=True,
82
83    # entry_points 指明了工程的入口,在本项目中就是facialattendancerecord模块下的main.py中的main方法
84    # 我这是命令行工具,安装成功后就是执行的这个命令
85
86    entry_points={
87        'console_scripts': [
88            'FacialAttendanceRecord=facialattendancerecord.main:main',
89        ],
90    },
91
92)
metadata

metadata其实有很多,下面是一张表

python 项目中的sqlach python 项目中的setup.py_ant_04



Classifiers

Classifiers可填写的内容也比较多,具体的可以参考这个链接 https://pypi.org/pypi?%3Aaction=list_classifiers

MANIFEST.in

该文件内容就是需要包含在分发包中的文件,示例如下

1include README.md
2include LICENSE
3include MANIFEST.in
4
5recursive-include config *.json
6
7prune build
8graft samples

其中includegraft是一个意思,区别在于前者是包含文件,后者是针对文件夹,prune是剔除文件夹,recursive-include相当于递归包含

requirements.txt

python 通过提供 requirements.txt 文件来对项目中依赖的第三方库进行整体安装,用户不用手动的一条条去敲 pip install 命令,只需要执行

1pip install -r requirements.txt

就可以安装项目所需要的所以软件包。requirements.txt 文件的格式一般是这样的

1Werkzeug==0.14.1
 2setuptools==36.4.0
 3SQLAlchemy_Utils==0.33.3
 4APScheduler==3.5.1
 5click==6.7
 6SQLAlchemy==1.2.1
 7Flask==0.12.2
 8Pillow==5.2.0
 9paho_mqtt==1.3.1
10scikit_learn==0.19.2
11tornado==5.1

每一行对应一个类库,等号右边的是对应库的版本号。对于稍大型的项目来讲,依赖的第三方库很多,所以,如果能够自动生成这个文件,将大大提升我们的工作效率。幸好有 pipreqs 这个工具,通过 pip 直接安装

1pip install pipreqs

然后进入到项目目录,执行命令

1pipreqs .

python 项目中的sqlach python 项目中的setup.py_cmake_05



参考资料