发布新日志

  • 使用py2exe生成可执行文件(转载)

    2009-09-27 11:04:46

    要使用py2exe,首先要编写一个编译脚本,然后通过Python运行编译脚本即可将其他的脚本编译成可执行文件。以下实例是将要编译成可执行文件的脚本。

        

    #file: MessageBox.py
    import win32api
    import win32con
    win32api.MessageBox(0, 'hi!', 'Python', win32con.MB_OK)

    以下实例是编译脚本。

        

    #file: setup.py
    import distutils
    import py2exe
    distutils.core.setup(windows=['MessageBox.py'])

    在Windows的cmd窗口中输入“setup.py  py2exe”,将得到如下输出:

        

    running py2exe
    *** searching for required modules ***
    *** parsing results ***
    creating python loader for extension 'win32api'
    creating python loader for extension 'unicodedata'
    creating python loader for extension 'bz2'
    *** finding dlls needed ***
    *** create binaries ***
    *** byte compile python files ***
    ************************************************************
    部分输出省略
    ************************************************************
    byte-compiling E:\book\code\py2exe\build\bdist.
    win32\winexe\temp\unicodedata.py
    to unicodedata.pyc
    byte-compiling E:\book\code\py2exe\build\bdist.
    win32\winexe\temp\win32api.py to
    win32api.pyc
    *** copy extensions ***
    *** copy dlls ***
    copying D:\Python25\lib\site-packages\py2exe\run_w.exe ->
    E:\book\code\py2exe\di
    st\MessageBox.exe

    *** binary dependencies ***
    Your executable(s) also depend on these dlls which are
    not included,
    you may or may not need to distribute them.

    Make sure you have the license if you distribute
    any of them, and
    make sure you don't distribute files belonging to the
    operating system.

    OLEAUT32.dll - C:\WINDOWS\system32\OLEAUT32.dll
    USER32.dll - C:\WINDOWS\system32\USER32.dll
    SHELL32.dll - C:\WINDOWS\system32\SHELL32.dll
    ole32.dll - C:\WINDOWS\system32\ole32.dll
    ADVAPI32.dll - C:\WINDOWS\system32\ADVAPI32.dll
    VERSION.dll - C:\WINDOWS\system32\VERSION.dll
    KERNEL32.dll - C:\WINDOWS\system32\KERNEL32.dll

    运行完编译脚本以后会在当前文件夹下生成dist和build两个目录。其中dist目录中就是编译生成的文件。如果要在其他未安装Python的 机器上运行编译好的程序,只要将dist目录复制到其他机器上即可。双击运行MessageBox.exe,如图10-4所示。

    在setup.py中除了导入必需的模块以外,只有一条语句。

    distutils.core.setup(windows=['MessageBox.py'])

    方括号中就是要编译的脚本名,前边的windows表示将其编译成GUI程序。如果要编译命令行界面的可执行文件,只要将windows改为 console。重新编译MessageBox.py后,双击运行,如图10-5所示。可以看到运行程序后多了一个命令行窗口。另外,如果需要将脚本编译 成Windows服务,则可以使用service选项。

Open Toolbar