python之程序打包

18.1 Distutils基礎

Distutils安裝腳本

from distutils.core import setup

setup(name='Hello',version='1.0',description='A simple example',author='Magnus Lie Hetland',py_modules=['hello'])

在setup函數內,不必提供所有這些信息。

確保在同一目下下存在名為hello.py的模塊文件

$python setup.py build

Distutils創建了叫做build的子目錄,其中包含名為lib的子目錄,並且把hello.py的一個副本放置在build/lib內。build目錄是Distutils組裝包的工作區。在安裝的時候不需要build命令。

安裝模塊

python setup.py install

18.2 打包

18.2.1 建立存檔文件

python setup.py sdist

在創建源代碼發佈程序時,程序同時會創建叫做MANIFEST的文件,其中包括所有文件的列表。MANIFEST.in文件是清單的模版,在指明安裝內容時要用到,可以使用如下命令來指定想要包含的文件。

18.3 編譯擴展

之前在17章關於palindrome程序的源代碼。假設已經在當前目錄中放置了源文件palindrome2.c,下面的setup.py腳本可以用於編譯:

from distutils.core import setup,Extension

setup(name='palindrome',version='1.0',ext_modules=[Extension('palindrome',['palindrome2.c'])])

如果只想在當前目錄編譯擴展:

python setup.py build_ext –inplace

from distutils.core import setup,Extension

setup(name='palindrome',version='1.0',ext_modules=[Extension('palindrome',['palindrome.c','palindrome.i'])])

如果使用和剛才一樣的命令運行腳本,可能會再次得到palindrome.so,但是這次就不用自己寫所有的包裝代碼了。

18.4 使用py2exe創建可執行程序

py2exe作為Distutils的擴展可用來創建可執行的windows程序。

Py2exe包可以創建擁有GUI的可執行文件。

print 'hello,world'

raw_input('Press <enter>')

讓我們再找個只包含這個名為hello.py的文件的空目錄,創建setup.py:

from distutils.core import setup

import py2exe

setup(console=['hello.py'])

運行腳本

python setup.exe py2exe

這樣會創建控制台應用程序以及位於dist子目錄中得其他一些文件。