[Python] 项目打包发布
一.setuptools
- 官方文档: Building and Distributing Packages with Setuptools
- 中文文档: Python包管理工具setuptools详解
1.使用过程
编辑: 先在项目主目录下编辑setup.py, 打包: python setup.py sdist 安装: sudo python setup.py install (--record files.txt) 卸载: sudo cat files.txt | sudo xargs rm -rf
2. setuptools工具的setup.py的模板
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. )
声明依赖包的语法:
This syntax consists of a project’s PyPI name, optionally followed by a comma-separated list of “extras” in square brackets, optionally followed by a comma-separated list of version specifiers.
A version specifier is one of the operators <, >, <=, >=, == or !=, followed by a version identifier.
Tokens may be separated by whitespace, but any whitespace or nonstandard characters within a project name or version identifier must be replaced with -.
其它例子:
docutils >= 0.3 # comment lines and \ continuations are allowed in requirement strings BazSpam ==1.1, ==1.2, ==1.3, ==1.4, ==1.5, \ ==1.6, ==1.7 # and so are line-end comments PEAK[FastCGI, reST]>=0.5a4 setuptools==0.5a7
详情可参考官方说明:Declaring Dependencies
二.Python项目的打包、发布和部署的常用方法比较
1. distutils - python自带的基本安装工具, 适用于非常简单的应用场景使用, 不支持依赖包的安装 通过distutils来打包,生成安装包,安装python包等工作,需要编写名为setup.py python脚本文件。 2. setuptools - 针对 distutils 做了大量扩展, 尤其是加入了包依赖机制。不支持python3,安装完setuptools后会有easy_install 3. distribute - 类似于setuptools,支持python3,安装完distribute后会有easy_install。 4. easy_install - setuptools 和 distribute 自带的安装脚本, 也就是一旦setuptools或distribute安装完毕, easy_install 也便可用了。 5. pip - 目标是取代easy_install。easy_install 有很多不足: 安装事务是非原子操作, 只支持 svn, 没有提供卸载命令, 安装一系列包时需要写脚本; pip 解决了以上问题, 已俨然成为新的事实标准, virtualenv 与它已经成为一对好搭档; 6. distutils2 - setuptools 和 distribute 的诞生是因为 distutils 的不济, 进而导致目前分化的状况。它将成为 Python 3.3 的标准库 packaging , 并在其它版本中以distutils2 的身份出现; 换句话说, 它和 pip 将联手结束目前混乱的状况。 7. virtualenv - 用来创建隔离的python环境,处理python环境的多版本和模块依赖。
常识
1. sudo apt-get install 安装的package存放在 /usr/lib/python2.7/dist-packages目录中
2. pip 或者 easy_install安装的package存放在/usr/local/lib/python2.7/dist-packages目录中
3. 手动从源代码安装的package存放在site-packages目录中
参考: