ansible源码解读

Ansible源码获取

Ansible Github:https://github.com/ansible

 Ansible目录结构

复制代码
$ tree -L 2 ansible-2.0.0.0
ansible-2.0.0.0
|-- bin                                # 可执行程序存放目录
|   |-- ansible
|   |-- ansible-doc -> ansible
|   |-- ansible-galaxy -> ansible
|   |-- ansible-playbook -> ansible
|   |-- ansible-pull -> ansible
|   `-- ansible-vault -> ansible
|-- CHANGELOG.md                      # 更新日志             
|-- contrib
|   |-- inventory
|   `-- README.md
|-- COPYING
|-- docs                              # 文档
|   `-- man
|-- examples                          # 主配置文件及hosts文件
|   |-- ansible.cfg
|   `-- hosts
|-- lib
|   |-- ansible
|   `-- ansible.egg-info
|-- Makefile
|-- MANIFEST.in
|-- packaging
|   |-- arch
|   |-- debian
|   |-- gentoo
|   |-- macports
|   |-- port
|   `-- rpm
|-- PKG-INFO
|-- README.md
|-- setup.cfg
|-- setup.py                                
`-- VERSION                           # 版本信息
复制代码

 setup.py解读

复制代码
#!/usr/bin/env python

import os
import sys

sys.path.insert(0, os.path.abspath('lib'))     # 将lib目录添加进环境变量 类似的方法sys.path.append() 两者区别:追加和插入第一个位置
from ansible import __version__, __author__
try:
    from setuptools import setup, find_packages
except ImportError:
    print("Ansible now needs setuptools in order to build. Install it using"
            " your package manager (usually python-setuptools) or via pip (pip"
            " install setuptools).")
    sys.exit(1)

setup(name='ansible',
      version=__version__,
      description='Radically simple IT automation',
      author=__author__,
      author_email='support@ansible.com',
      url='http://ansible.com/',
      license='GPLv3',
      # Ansible will also make use of a system copy of python-six if installed but use a
      # Bundled copy if it's not.
      install_requires=['paramiko', 'jinja2', "PyYAML", 'setuptools', 'pycrypto >= 2.6'],
      package_dir={ '': 'lib' },
      packages=find_packages('lib'),
      package_data={
         '': ['module_utils/*.ps1', 'modules/core/windows/*.ps1', 'modules/extras/windows/*.ps1', 'galaxy/data/*'],
      },
      classifiers=[
          'Development Status :: 5 - Production/Stable',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'Intended Audience :: Information Technology',
          'Intended Audience :: System Administrators',
          'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
          'Natural Language :: English',
          'Operating System :: POSIX',
          'Programming Language :: Python :: 2.6',
          'Programming Language :: Python :: 2.7',
          'Topic :: System :: Installation/Setup',
          'Topic :: System :: Systems Administration',
          'Topic :: Utilities',
      ],
      scripts=[
         'bin/ansible',
         'bin/ansible-playbook',
         'bin/ansible-pull',
         'bin/ansible-doc',
         'bin/ansible-galaxy',
         'bin/ansible-console',
         'bin/ansible-vault',
      ],
      data_files=[],
)
复制代码

Python源码包中的setup.py功能

setup.py功能:setup.py是python的一个项目发布管理工具。我们常常安装别人的代码也是借助setup.py

假设你要分发一个叫hello的模块,文件名hello.py,那么setup.py内容如下

复制代码
#!/usr/bin/env python
# coding: utf-8

from distutils.core import setup

setup(name='hello',
      version="1.0",
      py_modules=['hello'],
      )
复制代码

然后,运行python setup.py sdist为模块创建一个源码包

复制代码
C:UsersAdministratorPycharmProjectsuntitled>python setup.py sdist
running sdist
running check
warning: check: missing required meta-data: url
warning: check: missing meta-data: either (author and author_email) or (maintainer and maintainer_email) must be supplied
warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list)
warning: sdist: standard file not found: should have one of README, README.txt
writing manifest file 'MANIFEST'
creating hello-1.0
copying files to hello-1.0...
copying hello.py -> hello-1.0
copying setup.py -> hello-1.0
creating 'disthello-1.0.zip' and adding 'hello-1.0' to it
adding 'hello-1.0hello.py'
adding 'hello-1.0PKG-INFO'
adding 'hello-1.0setup.py'
removing 'hello-1.0' (and everything under it)
复制代码

  在当前目录下,会创建dist目录,里面有个文件名为hello-1.0.zip,这个就是可以分发的包。使用者拿到这个包后,解压,到hello-1.0目录下执行:python setup.py install,那么,hello.py就会被拷贝到python类路径下,可以被导入使用。

复制代码
C:UsersAdministratorPycharmProjectsuntitleddisthello-1.0>python setup.py install
running install
running build
running build_py
creating build
creating buildlib
copying hello.py -> buildlib
running install_lib
copying buildlibhello.py -> C:Python27Libsite-packages
byte-compiling C:Python27Libsite-packageshello.py to hello.pyc
running install_egg_info
Writing C:Python27Libsite-packageshello-1.0-py2.7.egg-info
复制代码

  对于Windows,可以执行python setup.py bdist_wininst生成一个exe文件;若要生成RPM包,执行python setup.py bdist_rpm,但系统必须有rpm命令的支持。可以运行下面的命令查看所有格式的支持:

复制代码
C:UsersAdministratorPycharmProjectsuntitleddisthello-1.0>python setup.py bdist --help-formats
List of available distribution formats:
  --formats=rpm      RPM distribution
  --formats=gztar    gzip'ed tar file
  --formats=bztar    bzip2'ed tar file
  --formats=ztar     compressed tar file
  --formats=tar      tar file
  --formats=wininst  Windows executable installer
  --formats=zip      ZIP file
  --formats=msi      Microsoft Installer
复制代码

setup函数还有一些参数:
1、packages
告诉Distutils需要处理那些包(包含__init__.py的文件夹)
2、package_dir
告诉Distutils哪些目录下的文件被映射到哪个源码包。一个例子:package_dir = {'': 'lib'},表示“root package”中的模块都在lib目录中。
3、ext_modules
是一个包含Extension实例的列表,Extension的定义也有一些参数。
4、ext_package
定义extension的相对路径
5、install_requires
定义依赖哪些模块
6、provides
定义可以为哪些模块提供依赖
7、scripts
指定python源码文件,可以从命令行执行。在安装时指定--install-script
8、package_data
通常包含与包实现相关的一些数据文件或类似于readme的文件。如果没有提供模板,会被添加到MANIFEST文件中。
9、data_files
指定其他的一些文件(如配置文件)

setup(...,
      data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),
                  ('config', ['cfg/data.cfg']),
                  ('/etc/init.d', ['init-script'])]
     )

规定了哪些文件被安装到哪些目录中。如果目录名是相对路径,则是相对于sys.prefix或sys.exec_prefix的路径。如果没有提供模板,会被添加到MANIFEST文件中。
执行sdist命令时,默认会打包哪些东西呢?
    所有由py_modules或packages指定的源码文件
    所有由ext_modules或libraries指定的C源码文件
    由scripts指定的脚本文件
    类似于test/test*.py的文件
    README.txt或README,setup.py,setup.cfg
    所有package_data或data_files指定的文件
还有一种方式是写一个manifest template,名为MANIFEST.in,定义如何生成MANIFEST文件,内容就是需要包含在分发包中的文件。一个MANIFEST.in文件如下:

include *.txt
recursive-include examples *.txt *.py
prune examples/sample?/build    

distutils模块讲解:https://docs.python.org/2/distutils/

相关知识扩展

setup.cfg

  setup.cfg提供一种方式,可以让包的开发者提供命令的默认选项,同时为用户提供修改的机会。对setup.cfg的解析,是在setup.py之后,在命令行执行前。
setup.cfg文件的形式类似于

[command]
option=value
...

  其中,command是Distutils的命令参数,option是参数选项,可以通过python setup.py --help build_ext方式获取。需要注意的是,比如一个选项是--foo-bar,在setup.cfg中必须改成foo_bar的格式

符合Distutils2的setup.cfg有些不同。包含一些sections:
1、global
定义Distutils2的全局选项,可能包含commands,compilers,setup_hook(定义脚本,在setup.cfg被读取后执行,可以修改setup.cfg的配置)
2、metadata
3、files
    packages_root:根目录
    packages
    modules
    scripts
    extra_files
4、command sections

setuptools

  上面的setup.py和setup.cfg都是遵循python标准库中的Distutils,而setuptools工具针对Python官方的distutils做了很多针对性的功能增强,比如依赖检查,动态扩展等。

内容还有很多,后期用到再进行扩展

原文地址:https://www.cnblogs.com/sunshine-1/p/7533614.html