使用py2exe转换python文件为可执行程序

本文介绍如何使用py2exe工具将Python脚本转换为Windows可执行文件。内容涵盖安装py2exe的方法、设置环境变量的过程、编写setup.py文件的示例及参数说明,最后通过命令行完成打包。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    py2exe可以将python脚本转换成在Windows上的可独立执行.exe程序的工具。可以让Python脚本在没有安装python工具的Windows系统上运行,方便脚本共享。

操作环境

    python2.7.12+Win32

Py2exe安装方法

1、py2exe模块下载。下载路径:py2exe官网,注意py2exe下载版本需要和本地的操作系统位数以及安装的python版本保持一致。

2、开始py2exe程序安装,安装方法按照提示默认安装即可。

Py2exe打包操作步骤

 1、进入python程序安装目录,如C:\Python27

 2、在Python安装路径(C:\Python27)创建一个setup.py文件。假设待转换的pyton脚本名为hello.py,脚本放置在Python安装路径下(C:\Python27)。示例如下:

c:\Python27>type setup.py(以下为添加内容)
from distutils.core import setup
import py2exe
options = {"py2exe":{"compressed": 1, "optimize": 2, "bundle_files": 1}}
setup(console=["hello.py"], options=options, zipfile=None)

参数说明:

   (1)  bundle_files有效值为(3:不打包,默认值,2:打包,但不打包Python解释器,1:打包,包括Python解释器)

   (2)  zipfile的有效值为(不填(默认): 生成一个library.zip文件,None:把所有东西打包进.exe文件中)

3、打开cmd窗口,切换到python的安装目录(C:\Python27),并执行命令python setup.py py2exe

c:\Python27>python setup.py py2exe
running py2exe
*** searching for required modules ***

............

*** copy dlls ***
copying c:\Python27\lib\site-packages\py2exe\run.exe -> c:\Python27\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.

USER32.dll - C:\Windows\system32\USER32.dll
SHELL32.dll - C:\Windows\system32\SHELL32.dll
ADVAPI32.dll - C:\Windows\system32\ADVAPI32.dll
WS2_32.dll - C:\Windows\system32\WS2_32.dll
GDI32.dll - C:\Windows\system32\GDI32.dll
KERNEL32.dll - C:\Windows\system32\KERNEL32.dll

4、在C:\Python27\dist目录下查看生成的可执行文件hello.exe。hello.exe即为打包后的可直接在windows上运行的程序。

c:\Python27\dist>dir
 驱动器 C 中的卷是 系统
 卷的序列号是 0000-0A6F

 c:\Python27\dist 的目录

2017/06/11  20:39    <DIR>          .
2017/06/11  20:39    <DIR>          ..
2017/06/11  20:39         3,960,694 hello.exe
2016/06/27  15:20           111,616 w9xpopen.exe
               2 个文件      4,072,310 字节
               2 个目录 17,607,745,536 可用字节

5、打包完成。

转载于:https://www.cnblogs.com/linyfeng/p/6740627.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值