日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python setup脚本编写

發布時間:2025/3/19 python 52 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python setup脚本编写 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文轉載自:http://lingxiankong.github.io/blog/2013/12/23/Python-setup/



前言

其實對于setup.py和setup.cfg的關注是從OpenStack的源碼包中開始的,OpenStack每個組件的發布時都是一個tar.gz包,同樣,我們直接從github上clone代碼后也會發現兩個文件的存在。當閱讀Nova或Ceilometer(其他組件可能也會涉及)的代碼時,發現setup.cfg中內容對于代碼的理解有很大的影響。那么,到底setup.py和setup.cfg是干什么的?

setup.py

我們從例子開始。假設你要分發一個叫foo的模塊,文件名foo.py,那么setup.py內容如下:

  • from distutils.core import setup
  • setup(name='foo',
  • version='1.0',
  • py_modules=['foo'],
  • )
  • 然后,運行python setup.py sdist為模塊創建一個源碼包

  • root@network:/kong/setup# 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 foo-1.0
  • making hard links in foo-1.0...
  • hard linking foo.py -> foo-1.0
  • hard linking setup.py -> foo-1.0
  • creating dist
  • Creating tar archive
  • removing 'foo-1.0' (and everything under it)
  • 在當前目錄下,會創建dist目錄,里面有個文件名為foo-1.0.tar.gz,這個就是可以分發的包。使用者拿到這個包后,解壓,到foo-1.0目錄下執行:python setup.py install,那么,foo.py就會被拷貝到python類路徑下,可以被導入使用。

  • root@network:/kong/setup/dist/foo-1.0# python setup.py install
  • running install
  • running build
  • running build_py
  • creating build
  • creating build/lib.linux-x86_64-2.7
  • copying foo.py -> build/lib.linux-x86_64-2.7
  • running install_lib
  • copying build/lib.linux-x86_64-2.7/foo.py -> /usr/local/lib/python2.7/dist-packages
  • byte-compiling /usr/local/lib/python2.7/dist-packages/foo.py to foo.pyc
  • running install_egg_info
  • Removing /usr/local/lib/python2.7/dist-packages/foo-1.0.egg-info
  • Writing /usr/local/lib/python2.7/dist-packages/foo-1.0.egg-info
  • root@network:/kong/setup/dist/foo-1.0# ll /usr/local/lib/python2.7/dist-packages/foo
  • foo-1.0.egg-info foo.py foo.pyc
  • 對于Windows,可以執行python setup.py bdist_wininst生成一個exe文件;若要生成RPM包,執行python setup.py bdist_rpm,但系統必須有rpm命令的支持。可以運行下面的命令查看所有格式的支持:

  • root@network:/kong/setup# 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、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
  • 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做了很多針對性的功能增強,比如依賴檢查,動態擴展等。很多高級功能我就不詳述了,自己也沒有用過,等用的時候再作補充。

    一個典型的遵循setuptools的腳本:

  • 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.
  • )
  • 如何讓一個egg可被執行?

  • setup(
  • # other arguments here...
  • entry_points = {
  • 'setuptools.installation': [
  • 'eggsecutable = my_package.some_module:main_func',
  • ]
  • }
  • )
  • 如何定義一個可選特性?

  • setup(
  • name="Project-A",
  • ...
  • extras_require = {
  • 'PDF': ["ReportLab>=1.2", "RXP"],
  • 'reST': ["docutils>=0.3"],
  • }
  • )
  • 特性如何使用呢?需要與entry points結合使用:

  • setup(
  • name="Project-A",
  • ...
  • entry_points = {
  • 'console_scripts': [
  • 'rst2pdf = project_a.tools.pdfgen [PDF]',
  • 'rst2html = project_a.tools.htmlgen',
  • # more script entry points ...
  • ],
  • }
  • )
  • 或者被其他project依賴:install_requires = ["Project-A[PDF]"]

    插件式開發

    我想大家最熟悉的就是這個特性了吧。比如一個博客系統想用不同的插件支持不同的語言輸出格式,那么就可以定義一個“entry point group”,不同的插件就可以注冊“entry point”,插件注冊的示例:

  • setup(
  • # ...
  • entry_points = {'blogtool.parsers': ['.rst = some_module:a_func']}
  • )
  • # 或者
  • setup(
  • # ...
  • entry_points = """
  • [blogtool.parsers]
  • .rst = some.nested.module:SomeClass.some_classmethod [reST]
  • """,
  • extras_require = dict(reST = "Docutils>=0.3.5")
  • )
  • Setuptools中的dependency_links

    Setuptools有一個功能叫做 dependency_links

    from setuptools import setup

  • setup(
  • # ...
  • dependency_links = [
  • "http://packages.example.com/snapshots/",
  • "http://example2.com/p/bar-1.0.tar.gz",
  • ],
  • )
  • 這一功能除去了依賴的抽象特性,直接把依賴的獲取url標在了setup.py里。就像在Go語言中修改依賴包一樣,我們只需要修改依賴鏈中每個包的 dependency_links 。

    管理依賴

    我們寫依賴聲明的時候需要在 setup.py 中寫好抽象依賴(install_requires),在 requirements.txt 中寫好具體的依賴,但是我們并不想維護兩份依賴文件,這樣會讓我們很難做好同步。 requirements.txt 可以更好地處理這種情況,我們可以在有 setup.py 的目錄里寫下一個這樣的 requirements.txt

  • --index https://pypi.python.org/simple/
  • -e .
  • 這樣 pip install -r requirements.txt 可以照常工作,它會先安裝該文件路徑下的包,然后繼續開始解析抽象依賴,結合 --index 選項后轉換為具體依賴然后再安裝他們。

    這個辦法可以讓我們解決一種類似這樣的情形:比如你有兩個或兩個以上的包在一起開發但是是分開發行的,或者說你有一個尚未發布的包并把它分成了幾個部分。如果你的頂層的包 依然僅僅按照“名字”來依賴的話,我們依然可以使用 requirements.txt 來安裝開發版本的依賴包:

  • --index https://pypi.python.org/simple/
  • -e https://github.com/foo/bar.git#egg=bar
  • -e .
  • 這會首先從 https://github.com/foo/bar.Git?來安裝包 bar , 然后進行到第二行 -e . ,開始安裝 setup 中的抽象依賴,但是包 bar 已經安裝過了, 所以 pip 會跳過安裝。

    Differences between distribute, distutils, setuptools and distutils2

    Distutils?is the standard tool used for packaging. It works rather well for simple needs, but is limited and not trivial to extend.

    Setuptools?is a project born from the desire to fill missing distutils functionality and explore new directions. In some subcommunities, it’s a de facto standard. It uses monkey-patching and magic that is frowned upon by Python core developers.

    Distribute?is a fork of Setuptools that was started by developers feeling that its development pace was too slow and that it was not possible to evolve it. Its development was considerably slowed when distutils2 was started by the same group. 2013-August update: distribute is merged back into setuptools and discontinued.

    Distutils2?is a new distutils library, started as a fork of the distutils codebase, with good ideas taken from setup tools (of which some were thoroughly discussed in PEPs), and a basic installer inspired by pip. The actual name you use to import Distutils2 is packaging in the Python 3.3+ standard library, or distutils2 in 2.4+ and 3.1–3.2. (A backport will be available soon.) Distutils2 did not make the Python 3.3 release, and it was put on hold.

    PBR

    pbr是setuptools的輔助工具,最初是為OpenStack開發(https://launchpad.NET/pbr),基于d2to1。

    A library for managing setuptools packaging needs in a consistent manner.

    pbr會讀取和過濾setup.cfg中的數據,然后將解析后的數據提供給setup.py作為參數。包含如下功能:
    1、從git中獲取Version、AUTHORS and ChangeLog信息
    2、Sphinx Autodoc。pbr會掃描project,找到所有模塊,生成stub files
    3、Requirements。pbr會讀取requirements.txt,生成setup函數需要的install_requires/tests_require/dependency_links

    這里需要注意,在requirements.txt文件的頭部可以使用:--index https://pypi.python.org/simple/,這一行把一個抽象的依賴聲明如 requests==1.2.0 轉變為一個具體的依賴聲明 requests 1.2.0 from pypi.python.org/simple/

    4、long_description。從README.rst, README.txt or README file中生成long_description參數

    使用pbr很簡單:

  • from setuptools import setup
  • setup(
  • setup_requires=['pbr'],
  • pbr=True,
  • )
  • 使用pbr時,setup.cfg中有一些配置。在[files]中,有三個key:
    packages:指定需要包含的包,行為類似于setuptools.find_packages
    namespace_packages:指定namespace packages
    data_files: 指定目的目錄和源文件路徑,一個示例:

  • [files]
  • data_files =
  • etc/pbr = etc/pbr/*
  • etc/neutron =
  • etc/api-paste.ini
  • etc/dhcp-agent.ini
  • etc/init.d = neutron.init
  • [entry_points]段跟setuptools的方式相同。

    Babel

    A collection of tools for internationalizing Python applications

    Babel是 Python 的一個國際化工具包,提供了對distutils或setuptools的支持,包含一些命令。

    1、compile_catalog
    類似于msgfmt工具,takes a message catalog from a PO file and compiles it to a binary MO file.

  • $ ./setup.py compile_catalog --directory foobar/locale --locale pt_BR
  • running compile_catalog
  • compiling catalog to foobar/locale/pt_BR/LC_MESSAGES/messages.mo
  • 2、extract_messages
    類似于xgettext,it can extract localizable messages from a variety of difference source files, and generate a PO (portable object) template file from the collected messages.

  • $ ./setup.py extract_messages --output-file foobar/locale/messages.pot
  • running extract_messages
  • extracting messages from foobar/__init__.py
  • extracting messages from foobar/core.py
  • ...
  • writing PO template file to foobar/locale/messages.pot
  • 3、update_catalog
    類似于msgmerge,it updates an existing translations catalog based on a PO template file (POT).

    setup.py和pip

    表面上,python setup.py install和pip install都是用來安裝python包的,實際上,pip提供了更多的特性,更易于使用。體現在以下幾個方面:

    • pip會自動下載依賴,而如果使用setup.py,則需要手動搜索和下載;
    • pip會自動管理包的信息,使卸載/更新更加方便和容易,使用pip uninstall即可。而使用setup.py,必須手動刪除,有時容易出錯。
    • pip提供了對virtualenv更好的整合。

    結語

    OK,講了這么多瑣碎的東西,現在去看看Nova或Ceilometer的setup腳本,是不是一下清晰了很多?!但說實話,setup.py的使用,我還不能講的特別清楚,需要在后續的實戰中學習。

    總結

    以上是生活随笔為你收集整理的python setup脚本编写的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。