本文是转载的,源地址: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内容如下:
fromdistutils.core importsetup
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 andauthor_email)or(maintainer andmaintainer_email)must be supplied
warning:sdist:manifest template’MANIFEST.in’does notexist (usingdefaultfile list)
warning:sdist:standard file notfound:should have one of README,README.txt
writing manifest file ‘MANIFEST’
creating foo-1.0
making hard links infoo-1.0…
hard linking foo.py ->foo-1.0
hard linking setup.py ->foo-1.0
creating dist
Creatingtar archive
removing ‘foo-1.0′(andeverything 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
Listof available distribution formats:
–formats=rpm RPM distribution