简介

py2exe 是 Python Distutils 的一个外部扩展,它可以把Python脚本转为可执行的Windows程序,无需安装Python即可运行。

你可以在官网得到更多资源。

说明

为了更好的完成本教程,你需要了解一些Python 的基本知识(你可以从 python.org’s getting started 页面开始)。你还需要知道 怎样从命令行提示符运行 Python 程序。

创建/测试 程序

创建setup 脚本文件 (setup.py)

运行setup 脚本

测试可执行程序

提供 Microsoft Visual C 运行时库

  • 5.1. Python 2.4 or 2.5
  • 5.2. Python 2.6, 2.7, 3.0, 3.1
  • 5.2.1. 创建C运行时库( C runtime DLL)
  • 5.2.1.1 win32ui 特例
  • 5.2.2. 运行这个可重新发行的 C 运行时安装程序
  1. 如果可以创建一个安装程序

1. 创建/测试程序

最重要的一步几乎总是第一步。好信息是 py2exe 通常在这一步很少或者几乎没有什么障碍。你处理Python 的绝大部分方法同样适用于 py2exe,Pyhton有很多模块是和 py2exe 无缝连接的。但是一些第三方模块需要额外花些时间,幸运的是这里有现成可用的帮助

 WorkingWithVariousPackagesAndModules。

print "Hello World!"

hello.py

C:\Tutorial>python hello.py
Hello World!

C:\Tutorial>

2. 创建 setup 脚本文件 (setup.py)

py2exe 在 Distutils 的基础上扩展了一个新的 "命令"。如果你安装过 Python 的第三方模块,那么你一定至少见过一个 distutils 命令:

C:\Tutorial>python setup.py install

"py2exe" 是一个新的 Distutils 命令, 当你导入 py2exe时就会加载进来。为了使用 py2exe ,你需要创建一个 setup.py 文件去告诉Distutils 和 py2exe 你想要做什么。

from distutils.core import setup
import py2exe

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

setup.py

  1. 在py2exe 下工作时,我们通常需要的 Distutils 的唯一部分就是 setup 函数,所以我们导入它。
  2. 一旦Distutils 加载完成,我们还需要加载 py2exe 以至于加载它的命令。
  3. 空一行总是好的!
  4. 调用 setup 告诉它我们想要一个单控制台应用程序,并且主入口是 "hello.py"。

3. 运行 setup 脚本

C:\Tutorial>python setup.py py2exe
running py2exe
*** searching for required modules ***
*** parsing results ***
creating python loader for extension 'zlib'
creating python loader for extension 'unicodedata'
creating python loader for extension 'bz2'
*** finding dlls needed ***
*** create binaries ***
*** byte compile python files ***
byte-compiling C:\Tutorial\build\bdist.win32\winexe\temp\bz2.py to bz2.pyc
byte-compiling C:\Tutorial\build\bdist.win32\winexe\temp\unicodedata.py to unicodedata.pyc
byte-compiling C:\Tutorial\build\bdist.win32\winexe\temp\zlib.py to zlib.pyc
skipping byte-compilation of c:\Python24\lib\StringIO.py to StringIO.pyc

[skipping many lines for brevity]

skipping byte-compilation of c:\Python24\lib\warnings.py to warnings.pyc
*** copy extensions ***
*** copy dlls ***
copying c:\Python24\lib\site-packages\py2exe\run.exe -> C:\Tutorial\dist\hello.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.

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

C:\Tutorial>

4. 测试可执行文件

C:\Tutorial>cd dist

C:\Tutorial\dist>hello.exe
Hello World