程式名稱:py2exe
說        明:將python (script)轉為exe執行檔,本說明是由py2exe的網頁文件翻譯改寫而成
網        站:http://starship.python.net/crew/theller/py2exe/
目前版本:0.6.3

假如你寫了一個程式叫 myscript.py 你要轉換成為windows的執行檔,首先你要寫一個setup-script, 下面有一個範例:
# setup.py
from distutils.core import setup
import py2exe

setup(console=["myscript.py"])

在shell下面執行
python setup.py py2exe --help   顯示所有可用參數
Options for 'py2exe' command:
  --optimize (-O)      optimization level: -O1 for "python -O", -O2 for
                       "python -OO", and -O0 to disable [default: -O0]
  --dist-dir (-d)      directory to put final built distributions in (default
                       is dist)
  --excludes (-e)      comma-separated list of modules to exclude
  --dll-excludes       comma-separated list of DLLs to exclude
  --ignores            comma-separated list of modules to ignore if they are
                       not found
  --includes (-i)      comma-separated list of modules to include
  --packages (-p)      comma-separated list of packages to include
  --compressed (-c)    create a compressed zipfile
  --xref (-x)          create and show a module cross reference
  --bundle-files (-b)  bundle dlls in the zipfile or the exe. Valid levels are
                       1, 2, or 3 (default)
  --ascii (-a)         do not automatically include encodings and codecs

usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help

#將會顯示所有py2exe可以使用的命令列的參數
接下來執行下面的命令,它會開始編譯該程式,在python的根目錄下建立一個dist目錄:
python setup.py py2exe

會建立 一個子目錄 dist\myscript , 包含執行檔 myscript.exe 和python24.dll和library.zip
如果你的script使用c-extension modules,它們也會被複製到這裏,包含所有執行時需要的 dlls.

這些檔案包含了你程式需要的所有東西,如果你要在別的電腦執行,必須包含了整個目錄

上述是建立一個console程式,如果你要一個GUI視窗程式,請取代console為windows

你可以一次建立多個exe檔,只要在console 或windows內填入多個程式使用list
console=(["myscript1.py","myscript2.py",........])

指定額外的檔案

一些應用程式執行時需要額外的檔案, 可能是環境檔, 字型, 圖檔, 不管是什麼.

py2exe 可以複製檔案到子目錄dist\myscript如果它們是指定在setup script中使用data_files 選項.
data_files 包含了一串的(target-dir, files)tuples, 檔案會被循序的複製.

這裏有個例子:

# setup.py
from distutils.core import setup
import glob
import py2exe

setup(console="myscript",
data_files=[("bitmaps",["bm/large.gif", "bm/small.gif"]),("fonts",glob("fonts\\*.fnt"))],)

這將建立一個子目錄bitmapsdist\myscript中,包含了兩個bitmaps,和一個子目 錄fonts, 包含了所有的字型 *.fnt檔.

Windows NT services

你可以建立Windows NT services  .

範列:

#setup.py
from distutils.core import setup
import py2exe

setup(service=["MyService"])

記住服務的啟動不同於一般的frozen應用程式:
script你提供的不是執行該script, 它是簡單的匯入和服務類別由包含在exe-file的C-code執行 .

一個Windows NT 服務必須向windows註冊, 你可以做它在命令列使用 -register .這個註冊服務使用內定的功能 (當做本地系統帳號記錄,手動啟動).同樣的你也可以 The service can be unregistered again by running the exe-file with the -remove option.

COM servers
COM servers是建立經由com_server的關鍵字在setup
#setup.py
from distutils.core import setup
import py2exe
setup(com_server=["win32com.server.interp"])
預設會產生DLL和EXE檔,你可以依照你的需要留下你要的檔

The bundle option(打包功能)
預設py2exe 建立這些檔在dist目錄下
  1. 一個或多個.exe檔
  2. python##.dll
  3. 一堆的.pyd,是exe檔所需要,或是其它的dll所需要
  4. 一個library.zip 檔包含了純的.pyc和.pyo如果你指定zipfile=None在setup script內,這個檔案會附加在執行檔之後
--bundle <level> 或 -b <level>可以用來切換建立較少檔案使用二位元檔延伸功能 (binary extensions),執行時期dll,甚至使用python-dll本身包裹到執行檔本身,或是插入library檔中

包裹pyds和dlls是從未解壓縮到檔案系統,替代的是它們被通透性的載入在執行的期間

指定level為2包含了.pyd和.dll檔案被至縮到zip檔或是執行檔內.因此dist目錄將包含你的exe檔,library.zip檔(如果你沒有指定zipfile=None),和python.dll的優點可以在執行期間載入延伸模組

使用level為1,同2,但包含了pythonXY.dll,優點是你只要散佈一個執行檔,但是這個檔案很大,另一個優點是Inproc COM 伺服器,將完整的隔離其它的python.缺點則是無法使用其它python的延伸功能,如果你使用這個功能會導致一個重大錯誤,並讓程式當機

範例
/lib/site-packages/py2exe/samples目錄下有幾個範例,可供你參考

版本資源

內定 py2exe 將會試著建立版本資源檔由setup-script中的 metadata 所提供,含版本version, 說明description, 和名稱 name. 當你指定整數及點時才可能成功其它字串不可包含其它的字 (像 '1.2.3'或 '0.7'有效, '1.2a3' 或 '5.7alpha' 將會無效).

你可以自定這些行為經由修改distutils環境檔,通常叫做 setup.cfg, 位於相同的目錄你的setup所儲存的地方.
樣本顯示可用的欄位如下:

[py2exe]
version-companyname=你公司的名稱
version-legalcopyright=版權
version-filedescription = 說明
version-fileversion = 檔案版本
version-legaltrademarks = 商標
version-productname = 產品名稱
version-productversion = 產品版本

注意在命令列無法設定版本.

它如何工作?

py2exe使用 python's modulefinder來載入你的程式並尋找所有 python和執行時所需要 的延伸模組. python模組是編譯到 .pyc .pyo 檔在暫存目錄中. Compiled extension modules (.pyd) 是同樣的同樣的給執行檔 獨立的解析.

一個zip-相容的檔案被建立包含了在目錄中所有檔案,且插入py2exe所提供的 custom python interpreter .

執行最後的程式叫myscript.exe, 將會安裝一個正要的 hook 如此模組可以由 zip-archive匯入,然後你的程式會被啟動.

簡單的情況下,只有 pythonxx.dll 是需要額外的 tomyscript.exe.如果,然而,你的程式需要額外的延伸模組,不幸的它們無法包含或是匯入zip-archive檔案中,因此它們需要額外分別的檔案 (並複製到dist\myscript 目錄中).

注意: py2exe 追蹤所有二位元相關的程式如l pyd'sdll's複製到dist 目錄中.py2exe已 經建立了一連串的系統檔案dlls不用被複製,但是這個表永遠無法完全

安裝

windows95/98/me,必須安裝unicode的套件,請到微軟的網站下載,下載完畢後,它是一個自解包unicows.exe,執行完畢後將unicows.dll複製到python.exe的目錄下

setup script的選項

>>> import py2exe
>>> help(py2exe)
會產生完整的說明,說明摘錄如下

說明
    New keywords for distutils' setup function specify what to build:  
        console
            list of scripts to convert into console exes
    
        windows
            list of scripts to convert into gui exes
    
        service
            list of module names containing win32 service classes
    
        com_server
            list of module names containing com server classes
    
        ctypes_com_server
            list of module names containing com server classes
    
        zipfile
            name of shared zipfile to generate, may specify a subdirectory,
            defaults to 'library.zip'
    
    
    py2exe options, to be specified in the options keyword to the setup function:
    
        unbuffered - if true, use unbuffered binary stdout and stderr
        optimize - string or int (0, 1, or 2)
    
        includes - list of module names to include
        packages - list of packages to include with subpackages
        ignores - list of modules to ignore if they are not found
        excludes - list of module names to exclude
        dll_excludes - list of dlls to exclude
    
        dist_dir - directory where to build the final files
        typelibs - list of gen_py generated typelibs to include (XXX more text needed)
    
    Items in the console, windows, service or com_server list can also be
    dictionaries to further customize the build process.  The following
    keys in the dictionary are recognized, most are optional:
    
        modules (SERVICE, COM) - list of module names (required)
        script (EXE) - list of python scripts (required)
        dest_base - directory and basename for the executable
                    if a directory is contained, must be the same for all targets
        create_exe (COM) - boolean, if false, don't build a server exe
        create_dll (COM) - boolean, if false, don't build a server dll
        bitmap_resources - list of 2-tuples (id, pathname)
        icon_resources - list of 2-tuples (id, pathname)
        other_resources - list of 3-tuples (resource_type, id, datastring)

PACKAGE CONTENTS
    boot_com_servers
    boot_common
    boot_ctypes_com_server
    boot_service
    build_exe
    mf
    py2exe_util
    resources (package)
    run_ctypes_dll
    run_dll
    run_isapi

CLASSES
    distutils.dist.Distribution
        Distribution
    
    class Distribution(distutils.dist.Distribution)
     |  Methods defined here:
     |  
     |  __init__(self, attrs)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from distutils.dist.Distribution:
     |  
     |  announce(self, msg, level=1)
     |  
     |  dump_option_dicts(self, header=None, commands=None, indent='')
     |  
     |  finalize_options(self)
     |      Set final values for all the options on the Distribution
     |      instance, analogous to the .finalize_options() method of Command
     |      objects.
     |  
     |  find_config_files(self)
     |      Find as many configuration files as should be processed for this
     |      platform, and return a list of filenames in the order in which they
     |      should be parsed.  The filenames returned are guaranteed to exist
     |      (modulo nasty race conditions).
     |      
     |      There are three possible config files: distutils.cfg in the
     |      Distutils installation directory (ie. where the top-level
     |      Distutils __inst__.py file lives), a file in the user's home
     |      directory named .pydistutils.cfg on Unix and pydistutils.cfg
     |      on Windows/Mac, and setup.cfg in the current directory.
     |  
     |  get_command_class(self, command)
     |      Return the class that implements the Distutils command named by
     |      'command'.  First we check the 'cmdclass' dictionary; if the
     |      command is mentioned there, we fetch the class object from the
     |      dictionary and return it.  Otherwise we load the command module
     |      ("distutils.command." + command) and fetch the command class from
     |      the module.  The loaded class is also stored in 'cmdclass'
     |      to speed future calls to 'get_command_class()'.
     |      
     |      Raises DistutilsModuleError if the expected module could not be
     |      found, or if that module does not define the expected class.
     |  
     |  get_command_list(self)
     |      Get a list of (command, description) tuples.
     |      The list is divided into "standard commands" (listed in
     |      distutils.command.__all__) and "extra commands" (mentioned in
     |      self.cmdclass, but not a standard command).  The descriptions come
     |      from the command class attribute 'description'.
     |  
     |  get_command_obj(self, command, create=1)
     |      Return the command object for 'command'.  Normally this object
     |      is cached on a previous call to 'get_command_obj()'; if no command
     |      object for 'command' is in the cache, then we either create and
     |      return it (if 'create' is true) or return None.
     |  
     |  get_command_packages(self)
     |      Return a list of packages from which commands are loaded.
     |  
     |  get_option_dict(self, command)
     |      Get the option dictionary for a given command.  If that
     |      command's option dictionary hasn't been created yet, then create it
     |      and return the new dictionary; otherwise, return the existing
     |      option dictionary.
     |  
     |  handle_display_options(self, option_order)
     |      If there were any non-global "display-only" options
     |      (--help-commands or the metadata display options) on the command
     |      line, display the requested info and return true; else return
     |      false.
     |  
     |  has_c_libraries(self)
     |  
     |  has_data_files(self)
     |  
     |  has_ext_modules(self)
     |  
     |  has_headers(self)
     |  
     |  has_modules(self)
     |  
     |  has_pure_modules(self)
     |  
     |  has_scripts(self)
     |  
     |  is_pure(self)
     |  
     |  parse_command_line(self)
     |      Parse the setup script's command line, taken from the
     |      'script_args' instance attribute (which defaults to 'sys.argv[1:]'
     |      -- see 'setup()' in core.py).  This list is first processed for
     |      "global options" -- options that set attributes of the Distribution
     |      instance.  Then, it is alternately scanned for Distutils commands
     |      and options for that command.  Each new command terminates the
     |      options for the previous command.  The allowed options for a
     |      command are determined by the 'user_options' attribute of the
     |      command class -- thus, we have to be able to load command classes
     |      in order to parse the command line.  Any error in that 'options'
     |      attribute raises DistutilsGetoptError; any error on the
     |      command-line raises DistutilsArgError.  If no Distutils commands
     |      were found on the command line, raises DistutilsArgError.  Return
     |      true if command-line was successfully parsed and we should carry
     |      on with executing commands; false if no errors but we shouldn't
     |      execute commands (currently, this only happens if user asks for
     |      help).
     |  
     |  parse_config_files(self, filenames=None)
     |  
     |  print_command_list(self, commands, header, max_length)
     |      Print a subset of the list of all commands -- used by
     |      'print_commands()'.
     |  
     |  print_commands(self)
     |      Print out a help message listing all available commands with a
     |      description of each.  The list is divided into "standard commands"
     |      (listed in distutils.command.__all__) and "extra commands"
     |      (mentioned in self.cmdclass, but not a standard command).  The
     |      descriptions come from the command class attribute
     |      'description'.
     |  
     |  reinitialize_command(self, command, reinit_subcommands=0)
     |      Reinitializes a command to the state it was in when first
     |      returned by 'get_command_obj()': ie., initialized but not yet
     |      finalized.  This provides the opportunity to sneak option
     |      values in programmatically, overriding or supplementing
     |      user-supplied values from the config files and command line.
     |      You'll have to re-finalize the command object (by calling
     |      'finalize_options()' or 'ensure_finalized()') before using it for
     |      real.
     |      
     |      'command' should be a command name (string) or command object.  If
     |      'reinit_subcommands' is true, also reinitializes the command's
     |      sub-commands, as declared by the 'sub_commands' class attribute (if
     |      it has one).  See the "install" command for an example.  Only
     |      reinitializes the sub-commands that actually matter, ie. those
     |      whose test predicates return true.
     |      
     |      Returns the reinitialized command object.
     |  
     |  run_command(self, command)
     |      Do whatever it takes to run a command (including nothing at all,
     |      if the command has already been run).  Specifically: if we have
     |      already created and run the command named by 'command', return
     |      silently without doing anything.  If the command named by 'command'
     |      doesn't even have a command object yet, create one.  Then invoke
     |      'run()' on that command object (or an existing one).
     |  
     |  run_commands(self)
     |      Run each command that was seen on the setup script command line.
     |      Uses the list of commands found and cache of command objects
     |      created by 'get_command_obj()'.
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from distutils.dist.Distribution:
     |  
     |  display_option_names = ['help_commands', 'name', 'version', 'fullname'...
     |  
     |  display_options = [('help-commands', None, 'list all available command...
     |  
     |  global_options = [('verbose', 'v', 'run verbosely (default)', 1), ('qu...
     |  
     |  negative_opt = {'quiet': 'verbose'}

DATA
    __version__ = '0.6.3'

VERSION
    0.6.3