制作python模塊安裝包[原創]
Python的第三方模塊越來越豐富,涉及的領域也非常廣,如科學計算、圖片處理、web應用、GUI開發等。當然也可以將自己寫的模塊進行打包或發布。一簡單的方法是將你的類包直接copy到Python的lib目錄,但此方式不便于管理與維護,存在多個Python版本時會非常混亂。現介紹如何編寫setup.py來對一個簡單的Python模塊進行打包。
一、編寫模塊
進入項目目錄
#cd /home/pysetup
#vi foo.py
-
view plainprint? class MyClass(): def __init__(self): self.blog = "http://blog.liuts.com" def printblog(self): print self.blog def printBblog(self): print self.blog.swapcase()
二、編寫setup.py
#vi setup.py
view plainprint? from distutils.core import setup setup(name='Myblog', version='1.0', description='My Blog Distribution Utilities', author='Liu tiansi', author_email='[email protected]', url='http://blog.liuts.com', py_modules=['foo'], )

三、setup.py參數說明
#Python setup.py build # 編譯 #Python setup.py install #安裝 #Python setup.py sdist #生成壓縮包(zip/tar.gz) #Python setup.py bdist_wininst #生成NT平臺安裝包(.exe) #Python setup.py bdist_rpm #生成rpm包
或者直接"bdist 包格式",格式如下:
#Python setup.py bdist --help-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
四、打包
#Python setup.py sdist
running sdist 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 Myblog-1.0 making hard links in Myblog-1.0... hard linking foo.py -> Myblog-1.0 hard linking setup.py -> Myblog-1.0 creating dist tar -cf dist/Myblog-1.0.tar Myblog-1.0 gzip -f9 dist/Myblog-1.0.tar removing 'Myblog-1.0' (and everything under it)
提示兩條warning可以忽略,不影響打包,當然一個完善的項目必須有README及MANIFEST.in(項目文件清單)文件。
#ls dist
Myblog-1.0.tar.gz
五、安裝
#tar -zxvf Myblog-1.0.tar.gz
#cd Myblog-1.0.tar.gz
#Python setup.py install (此命令大家再熟悉不過了)
running install running build running build_py creating build/lib.Linux-x86_64-2.6 copying foo.py -> build/lib.Linux-x86_64-2.6 running install_lib copying build/lib.Linux-x86_64-2.6/foo.py -> /usr/local/lib/Python2.6/dist-packages byte-compiling /usr/local/lib/Python2.6/dist-packages/foo.py to foo.pyc running install_egg_info Writing /usr/local/lib/Python2.6/dist-packages/Myblog-1.0.egg-info
六、測試
>>> from foo import MyClass >>> app=MyClass() >>> app.print printblog() >>> app.printblog() http://blog.liuts.com >>> app.printBblog() HTTP://BLOG.LIUTS.COM >>>
參考文獻:
http://docs.Python.org/distutils/setupscript.html
如大家有什么疑問或感興趣的話題可以通過weibo與我交流:http://t.qq.com/yorkoliu