51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 992|回复: 0
打印 上一主题 下一主题

[python] Python项目管理、构建工具实用干货推荐!

[复制链接]
  • TA的每日心情
    擦汗
    昨天 08:59
  • 签到天数: 1021 天

    连续签到: 2 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2022-8-23 11:22:29 | 只看该作者 回帖奖励 |正序浏览 |阅读模式
     Python 历时这么久以来至今还未有一个事实上标准的项目管理及构建工具,以至于造成 Python 项目的结构与构建方式五花八门。这或许是体现了 Python 的自由意志。
      不像 Java 在经历了最初的手工构建,到半自动化的 Ant, 再到 Maven 基本就是事实上的标准了。其间 Maven 还接受了其他的 Gradle(Android 项目主推), SBT(主要是 Scala 项目), Ant+Ivy, Buildr 等的挑战,但都很难撼动 Maven 的江湖地位,而且其他的差不多遵循了 Maven 的目录布局。
      回到 Python,产生过 pip, pipenv, conda 那样的包管理工具,但对项目的目录布局没有任何约定。
      关于构建很多还是延续了传统的 Makefile 的方式,再就是加上 setup.py 和 build.py 用程序代码来进行安装与构建。关于项目目录布局,有做成项目模板的,然后做成工具来应用项目模板。
      下面大概浏览一下四个工具的使用:
      1. CookieCutter
      2.  PyScaffold
      3.  PyBuilder
      4. Poetry
      CookieCutter 一个经典的 Python 项目目录结构
    $ pip install cookiecutter
      $ cookiecutter gh:audreyr/cookiecutter-pypackage   
      # 以 github 上的 audreyr/cookiecutter-pypackage 为模板,再回答一堆的问题生成一个 Python 项目
      ......
      project_name [Python Boilerplate]: sample
      ......

    最后由 cookiecutter 生成的项目模板是下面的样子:

    1. $ tree sample
    2.   sample
    3.   ├── AUTHORS.rst
    4.   ├── CONTRIBUTING.rst
    5.   ├── HISTORY.rst
    6.   ├── LICENSE
    7.   ├── MANIFEST.in
    8.   ├── Makefile
    9.   ├── README.rst
    10.   ├── docs
    11.   │   ├── Makefile
    12.   │   ├── authors.rst
    13.   │   ├── conf.py
    14.   │   ├── contributing.rst
    15.   │   ├── history.rst
    16.   │   ├── index.rst
    17.   │   ├── installation.rst
    18.   │   ├── make.bat
    19.   │   ├── readme.rst
    20.   │   └── usage.rst
    21.   ├── requirements_dev.txt
    22.   ├── sample
    23.   │   ├── __init__.py
    24.   │   ├── cli.py
    25.   │   └── sample.py
    26.   ├── setup.cfg
    27.   ├── setup.py
    28.   ├── tests
    29.   │   ├── __init__.py
    30.   │   └── test_sample.py
    31.   └── tox.ini
    32.   3 directories, 26 files
    复制代码
    这大概是当前比较流行的目录结构的主体框架,主要元素是:

    1.  $ tree sample
    2.   sample
    3.   ├── Makefile
    4.   ├── README.rst
    5.   ├── docs
    6.   │   └── index.rst
    7.   ├── requirements.txt
    8.   ├── sample
    9.   │   ├── __init__.py
    10.   │   └── sample.py
    11.   ├── setup.cfg
    12.   ├── setup.py
    13.   └── tests
    14.      ├── __init__.py
    15.      └── test_sample.py
    复制代码
    项目 sample 目录中重复 sample 目录中放置 Python 源文件,tests 目录中是测试文件,再加一个 docs 目录放文档,README.rst, 其他的用于构建的 setup, setup.cfg 和 Makefile 文件。
      这其实是一个很经典的 Python 项目结构,接下来的构建就用 make 命令了,输入 make 会看到定义在 Makefile 文件中的指令。
    1. $ make
    2.   clean                remove all build, test, coverage and Python artifacts
    3.   clean-build          remove build artifacts
    4.   clean-pyc            remove Python file artifacts
    5.   clean-test           remove test and coverage artifacts
    6.   lint                 check style
    7.   test                 run tests quickly with the default Python
    8.   test-all             run tests on every Python version with tox
    9.   coverage             check code coverage quickly with the default Python
    10.   docs                 generate Sphinx HTML documentation, including API docs
    11.   servedocs            compile the docs watching for changes
    12.   release              package and upload a release
    13.   dist                 builds source and wheel package
    14.   install              install the package to the active Python's site-packages
    复制代码
    为使用上面的构建过程,需要安装相应的包,如 tox, wheel, coverage, sphinx, flake8, 它们都可以通过  pip 来安装。之后就可以 make test, make coverage, make docs,make dist 等。其中 make docs 可以生成一个很漂亮的 Web 文档。
      PyScaffold 创建一个项目
      PyScaffold 顾名思义,它是一个用来创建 Python 项目脚手架的工具,安装和使用:
    1. $ pip install pyscaffold
    2.   $ putup sample
    复制代码
    这样创建了一个 Python 项目,目录结构与前面  cookiecutter 所选的模板差不多,只不过它把源文件放在了 src 目录,而非 sample 目录。
    1. $ tree sample
    2.   sample
    3.   ├── AUTHORS.rst
    4.   ├── CHANGELOG.rst
    5.   ├── CONTRIBUTING.rst
    6.   ├── LICENSE.txt
    7.   ├── README.rst
    8.   ├── docs
    9.   │   ├── Makefile
    10.   │   ├── _static
    11.   │   ├── authors.rst
    12.   │   ├── changelog.rst
    13.   │   ├── conf.py
    14.   │   ├── contributing.rst
    15.   │   ├── index.rst
    16.   │   ├── license.rst
    17.   │   ├── readme.rst
    18.   │   └── requirements.txt
    19.   ├── pyproject.toml
    20.   ├── setup.cfg
    21.   ├── setup.py
    22.   ├── src
    23.   │   └── sample
    24.   │       ├── __init__.py
    25.   │       └── skeleton.py
    26.   ├── tests
    27.   │   ├── conftest.py
    28.   │   └── test_skeleton.py
    29.   └── tox.ini
    复制代码
    整个项目的构建就要用 tox 这个工具了。tox 是一个自动化测试和构建工具,它在构建过程中可创建 Python 虚拟环境,这让测试和构建能有一个干净的环境。
      tox -av 能显示出定义在 tox.ini 中所有的任务:
    1. $ tox -av
    2.   default environments:
    3.   default   -> Invoke pytest to run automated tests
    4.   additional environments:
    5.   build     -> Build the package in isolation according to PEP517, see https://github.com/pypa/build
    6.   clean     -> Remove old distribution files and temporary build artifacts (./build and ./dist)
    7.   docs      -> Invoke sphinx-build to build the docs
    8.   doctests  -> Invoke sphinx-build to run doctests
    9.   linkcheck -> Check for broken links in the documentation
    10.   publish   -> Publish the package you have been developing to a package index server. By default, it uses testpypi. If you really want to publish your package to be publicly accessible in PyPI, use the `-- --repository pypi` option.
    复制代码
    要执行哪个命令便用 tox -e build, tox -e docs 等
      在我体验 tox 命令过程中,每一步好像都比较慢,应该是创建虚拟机要花些时间。
      PyBuilder
      最好再看另一个构建工具 PyBuilder, 它所创建出的目录结构很接近于 Maven, 下面来瞧瞧
    1. $ pip install pybuilder
    2.   $ mkdir sample && cd sample    # 项目目录需手工创建
    3.   $ pyb --start-project          # 回答一些问题后创建所需的目录和文件
    复制代码
    完后看下它的目录结构:
    1. $ tree sample
    2.   .
    3.   ├── build.py
    4.   ├── docs
    5.   ├── pyproject.toml
    6.   ├── setup.py
    7.   └── src
    8.      ├── main
    9.      │   ├── python
    10.      │   └── scripts
    11.      └── unittest
    12.          └── python
    复制代码
    构建过程仍然是用 pyb 命令,可用 pyb -h 查看帮助,pyb -t 列出所有的任务, PyBuilder 的任务是以插件的方式加入的,插件配置在  build.py 文件中。
    1.  $ pyb -t sample
    2.   Tasks found for project "sample":
    3.                    analyze -  Execute analysis plugins.
    4.                              depends on tasks: prepare run_unit_tests
    5.                      clean - Cleans the generated output.
    6.            compile_sources - Compiles source files that need compilation.
    7.                              depends on tasks: prepare
    8.                   coverage - <no description available>
    9.                              depends on tasks: verify
    10.                    install - Installs the published project.
    11.                              depends on tasks: package publish(optional)
    12.                    package - Packages the application. Package a python application.
    13.                              depends on tasks: compile_sources run_unit_tests(optional)
    14.                    prepare - Prepares the project for building. Creates target VEnvs
    15.          print_module_path - Print the module path.
    16.         print_scripts_path - Print the script path.
    17.                    publish - Publishes the project.
    18.                              depends on tasks: package verify(optional) coverage(optional)
    19.      run_integration_tests - Runs integration tests on the packaged application.
    20.                              depends on tasks: package
    21.             run_unit_tests - Runs all unit tests. Runs unit tests based on Python's unittest module
    22.                              depends on tasks: compile_sources
    23.                     upload - Upload a project to PyPi.
    24.                     verify - Verifies the project and possibly integration tests.
    25.                              depends on tasks: run_integration_tests(optional)
    26.   $ pyb run_unit_tests sample
    复制代码
    PyBuilder 也是在构建或测试之前创建虚拟环境, 从 0.12.9 版开始可通过参数 --no-venvs 跳过创建虚拟环境这一步。使用了 --no-venvs 的话 Python 代码将会在运行  pyb 的当前 Python 环境中执行,所需的依赖将要手工安装。
      项目的依赖也要定义在 build.py 文件中。
    1. @init
    2.   def set_properties(project):
    3.      project.depends_on('boto3', '>=1.18.52')
    4.      project.build_depends_on('mock')
    复制代码
    随后在执行 pyb 创建虚拟环境时就会安装上面的依赖,并在其中运行测试与构建。
      Poetry
      最后一个 Poetry, 感觉这是一个更为成熟,项目活跃度也更高的 Python 构建,它有着更强大的信赖管理功能,用 poetry add boto3 就能添加依赖,poetry show --tree 显示出依赖树。看下如何安装及创建一个项目
    1.  $ pip install poetry
    2.   $ poetry new sample
    复制代码
    它创建的项目比上面都简单
    1. $ tree sample
    2.   sample
    3.   ├── README.rst
    4.   ├── pyproject.toml
    5.   ├── sample
    6.   │   └── __init__.py
    7.   └── tests
    8.      ├── __init__.py
    9.      └── test_sample.py
    复制代码
    如果给 poetry new 带上 --src 参数,那么源文件目录 sample 会放在 src 目录下,即 sample/src/sample.
      poetry init 会在当前目录中生成 pyproject.toml 文件,目录等的生成需手动完成。
      它不关注文档的生成,代码规范的检查,代码覆盖率都没有。它的项目配置更集中,全部在 pyproject.toml 文件中,toml 是什么呢?它是一种配置文件的格式 Tom's Obvious, Minimal Language (https://github.com/toml-lang/toml).
      pyproject.toml 有些类似 NodeJS 的 package.json 文件,比如 poetry add, poetry install 命令的行。
    1. # 往 pyproject.toml 中添加对  boto3 的依赖并安装(add 还能从本地或 git 来安装依赖 ),
    2.   poetry add boto3   
    3.   # 将依照 pyproject.toml 文件中定义安装相应的依赖到当前的 Python 虚拟环境中
    4.   # 比如在 <test-venv>/lib/python3.9/site-packages 目录中,安装好模块后也可让测试用例使用
    5.   poetry install
    复制代码
    其他主要的:
    1. 1.  poetry build    # 构建可安装的 *.whl 和 tar.gz 文件
    2.   2.  poetry shell    # 会根据定义在 pyproject.toml 文件中的依赖创建并使用虚拟环境
    3.   3.  poetry run pytest    # 运行使用 pytest 的测试用例,如 tests/test_sample.py
    4.   4.  poetry run python -m unittest tests/sample_tests.py  # 运行 unittest 测试用例
    5.   5.  poetry export --without-hashes --output requirements.txt  # 导出 requirements.txt 文件, --dev  导出含 dev 的依赖,或者用 poetry export --without-hashes > requirements.txt
    复制代码
    poetry run 能执行任何系统命令,只是它会在它要的虚拟环境中执行。所以可以想见,poetry 的项目要生成文档或覆盖率都必须用 poetry run ... 命令来支持 sphinx, coverage 或 flake8。
      在 sample 目录(与 pyproject.toml 文件平级)中创建文件 my_module.py, 内容为
    1. def main():
    2.      print('hello poetry')
    复制代码
    然后在 pyproject.toml 中写上。
    1. [tool.poetry.scripts]
    2.   my-script="sample.my_module:main"
    复制代码
    再执行
    1.  $ poetry run my-script
    复制代码
    就会输出 "hello poetry"。
      通过对以上四个工具的认识,项目结构的复杂度由 cookiecutter-pyproject -> PyScaffold -> PyBuilder -> Poetry 依次降低,使用的难度大略也是相同的顺序。










    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-9-20 16:50 , Processed in 0.059303 second(s), 24 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表