将py生成为exe文件

py2exe是一个使Python脚本能在没有Python环境的Windows系统上运行的工具。通过创建distutils setup脚本并导入py2exe,可以将Python脚本打包成exe文件。此外,还可以通过data_files选项指定额外的运行时文件,如配置文件、字体等。py2exe还能创建Windows NT服务和COM服务器,并提供了捆绑选项来减少生成的文件数量,甚至将所有依赖项整合到单一exe中。

Using py2exe

Assuming you have written a python script myscript.py which you want to convert into an executable windows program, able to run on systems without a python installation. If you don't already have written a distutils setup-script, write one, and insert the statement import py2exe before the call to the setup function:

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

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

Running

python setup.py py2exe --help

will display all available command-line flags to the py2exe command.

Now you can call the setup script like in this way:

python setup.py py2exe

and a subdirectory dist will be created, containing the files myscript.exe, python23.dll, and library.zip. If your script uses compiled C extension modules, they will be copied here as well, also all dlls needed at runtime (except the system dlls).

These files include everything that is needed for your program, and you should distribute the whole directory contents.

The above setup script creates a console program, if you want a GUI program without the console window, simply replace console=["myscript.py"] with windows=["myscript.py"].

py2exe can create more than one exe file in one run, this is useful if you have a couple of related scripts. Pass a list of all scripts in the console and/or windows keyword argument.

Specifying additional files

Some applications need additional files at runtime, like configuration files, fonts, or bitmaps.

py2exe can copy these files into subdirectories of dist if they are specified in the setup script with the data_files option. data_files should contain a sequence of (target-dir, files) tuples, where files is a sequence of files to be copied.

Here's an example:

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

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

This would create a subdirectory dist/bitmaps, containing the two .gif files, and a subdirectory dist/fonts, containing all the .fnt files.

Windows NT services

You can build Windows NT services by passing a service keyword argument to the setup function, the value must be a list of Python module names containing a service class (identified by the _svc_name_ attribute):

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

setup(service=["MyService"])

The built service executables are able to install and remove themselves by calling them with certain command line flags, run the exe with the -help argument to find out more.

COM servers

COM servers are built by passing a com_server keyword argument to the setup function, again the value must be a list of Python module names containing one or more COM server classes (identified by their _reg_progid_ attribute):

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

setup(com_server=["win32com.server.interp"])

By default both DLL and EXE servers are built, you should simply delete those you don't need.

The bundle option

By default py2exe creates these files in the dist directory which you must deploy:

  1. One (or more) .exe files
  2. The python##.dll
  3. A couple of .pyd files which are the compiled extensions that the exe files need, plus any other .dll files that the extensions need.
  4. A library.zip file which contains the compiled pure python modules as .pyc or .pyo files (if you have specified 'zipfile=None' in the setup script this file is append to the .exe files and not present in the dist-directory).

The --bundle <level> or -b <level> command line switch will create less files because binary extensions, runtime dlls, and even the Python-dll itself is bundled into the executable itself, or inside the library-archive if you prefer that.

The bundled pyds and dlls are never unpacked to the file system, instead they are transparently loaded at runtime from the bundle. The resulting executable appears to be statically linked.

Specifying a level of 2 includes the .pyd and .dll files into the zip-archive or the executable. Thus, the dist directory will contain your exe file(s), the library.zip file (if you haven't specified 'zipfile=None'), and the python dll. The advantage of this scheme is that the application can still load extension modules from the file system if you extend sys.path at runtime.

Using a level of 1 includes the .pyd and .dll files into the zip-archive or the executable itself, and does the same for pythonXY.dll. The advantage is that you only need to distribute one file per exe, which will however be quite large. Another advantage is that inproc COM servers will run completely isolated from other Python interpreters in the same exe. The disadvantage of this scheme is that it is impossible to load other extensions from the file system, the application will crash with a fatal Python error if you try this. I have still to find a way to prevent this and raise an ImportError instead - any suggestions how this can be implemented would be very welcome.

The bundle-option has been tested with some popular extensions, but of course there's no guarantee that any extension will work in bundled form - be sure to test the executable (which you should do anyway).

The bundle option achieves its magic by code which emulates the Windows LoadLibrary api, it is compiled into the exe-stubs that py2exe uses. For experimentation, it is also installed as a normal Python extension _memimporter.pyd in the lib/site-packages directory. The Python module zipextimported.py in the same directory demonstrates how it can be used to load binary extensions from zip-files.

Samples

The py2exe-installer installs some examples into the lib/site-packages/py2exe/samples directory, demonstrating several simple and advances features.

The singlefile subdirectory contains two samples which are built as single-file executables: a trivial wxPython gui program, and a pywin32 dll COM server module.

How does it work?

py2exe uses python's modulefinder to examine your script and find all python and extension modules needed to run it. Pure python modules are compiled into .pyc or .pyo files in a temporary directory. Compiled extension modules (.pyd) are also found and parsed for binary dependencies.

A zip-compatible archive is built, containing all python files from this directory. Your main script is inserted as a resource into a custom embedded python interpreter supplied with py2exe, and the zip-archive is installed as the only item on sys.path.

In simple cases, only pythonxx.dll is needed in addition to myscript.exe. If, however, your script needs extension modules, unfortunately those cannot be included or imported from the zip-archive, so they are needed as separate files (and are copied into the dist directory).

Attention: py2exe tries to track down all binary dependencies for all pyds and dlls copied to the dist directory recursively, and copies all these dependend files into the dist directory. py2exe has a builtin list of some system dlls which are not copied, but this list can never be complete.

Installing py2exe

Download and run the installer py2exe-0.6.3.win32-py2.3.exe (for Python 2.3), or py2exe-0.6.3.win32-py2.4.exe (for Python 2.4).

This installs py2exe together with some samples, the samples are in the lib/site-packages/py2exe/samples subdirectory.

For Windows 95/98/Me, you need the Microsoft Layer for Unicode on Windows 95/98/ME Systems (MSLU) dll from here (Internet Explorer is required to download it: Scroll down to the Win95/98/Me section).

Download and run the self-extracting unicows.exe file, and copy the unpacked unicows.dll file in the directory which contains your python.exe. Note that this is only needed on the machine where you want to build executables with py2exe, it is not required on the machine where you want to run the created programs.

If you use py2exe to build COM clients or servers, win32all build 163 (or later) is strongly recommened - it contains much better support for frozen executables.

本文来自 www.py2exe.org

<think>我们使用pyinstaller来打包Python脚本为exe可执行文件。根据引用[1]和引用[2]的内容,以下是详细步骤和常用参数说明: ### 打包步骤 1. **安装pyinstaller** 在命令行中执行: ```bash pip install pyinstaller ``` 2. **进入脚本所在目录** 在资源管理器中打开脚本所在文件夹,然后在地址栏输入`cmd`并按回车,即可在当前目录打开命令行。 3. **执行打包命令** - **生成单个exe文件**(推荐简单程序使用): ```bash pyinstaller -F 你的脚本.py ``` 生成结果:在`dist`文件夹中会有一个单独的exe文件。 - **生成带依赖库的文件夹**(推荐复杂程序使用): ```bash pyinstaller -D 你的脚本.py ``` 生成结果:在`dist`文件夹中会有一个与脚本同名的文件夹,包含exe文件和各种依赖库。 4. **可选参数** - `-w`:不显示控制台窗口(适用于GUI程序,如tkinter程序) - `-i 图标文件.ico`:设置exe的图标 - `--add-data "源路径;目标路径"`:添加数据文件(如图片、配置文件等) ### 完整示例 假设有一个tkinter程序`gui_app.py`,并希望: - 打包成单个exe - 不显示控制台 - 使用`app.ico`作为图标 命令如下: ```bash pyinstaller -F -w -i app.ico gui_app.py ``` ### 注意事项 1. **路径问题** 如果程序中有读取文件的操作,打包后路径会改变,建议使用以下方法获取正确路径: ```python import sys import os # 获取临时资源目录(适用于单文件模式) if getattr(sys, 'frozen', False): base_path = sys._MEIPASS else: base_path = os.path.abspath(".") ``` 2. **添加资源文件** 对于需要额外资源(如图片)的程序,使用`--add-data`指定: ```bash pyinstaller -F --add-data "images;images" your_script.py ``` 然后在代码中通过`base_path`拼接资源路径。 3. **防病毒软件误报** 部分杀毒软件可能误报pyinstaller生成exe,可尝试以下方法: - 使用`-D`模式(文件夹形式) - 使用代码签名证书签名 - 在打包前用PyArmor等工具混淆代码 ### 常见问题解决 - **打包后运行闪退**: 在命令行中运行exe查看错误信息(去掉`-w`参数),或使用`--debug`模式打包。 - **图标不生效**: 确保图标文件是`.ico`格式,且尺寸包含256x256。 - **文件太大**: 使用虚拟环境打包可显著减小体积: ```bash # 创建虚拟环境 python -m venv venv venv\Scripts\activate pip install pyinstaller pip install 你的依赖包 pyinstaller -F your_script.py ``` > 引用说明:打包方法参考了pyinstaller官方文档和常见打包实践[^1][^2]。 §§相关问题§§ 1. 如何解决PyInstaller打包后文件过大的问题? 2. PyInstaller打包时如何包含数据文件(如图片、配置文件)? 3. 打包后的exe程序被误报病毒怎么办? 4. 如何为PyInstaller打包的exe添加版本信息?</think>### Python打包生成exe可执行文件完整指南 根据引用内容,使用PyInstaller打包Python脚本为exe文件的步骤如下: #### 1. 安装PyInstaller ```bash pip install pyinstaller ``` #### 2. 基本打包命令 ```bash # 生成单个exe文件(推荐) pyinstaller -F your_script.py # 生成包含依赖库的文件pyinstaller -D your_script.py ``` #### 3. 常用参数详解 | 参数 | 说明 | 示例 | |------|------|------| | `-F` | 生成单个exe文件 | `pyinstaller -F app.py` | | `-D` | 创建包含依赖库的文件夹 | `pyinstaller -D app.py` | | `-w` | 关闭控制台窗口(GUI程序必备) | `pyinstaller -F -w app.py` | | `-i` | 添加程序图标 | `pyinstaller -F -i icon.ico app.py` | | `--add-data` | 添加资源文件 | `pyinstaller --add-data "images;images" app.py` | | `-c` | 显示控制台(默认) | `pyinstaller -c app.py` | | `--onefile` | 同`-F` | `pyinstaller --onefile app.py` | #### 4. 完整打包示例 ```bash # 打包图形界面程序(带图标,不显示控制台) pyinstaller -F -w -i app_icon.ico main.py # 打包控制台程序(带数据文件pyinstaller -F --add-data "data/*;data" cli_tool.py ``` #### 5. 打包后文件位置 - 单个exe文件:`dist/your_script.exe` - 文件夹形式:`dist/your_script/`目录 - 中间文件:`build/`目录(可删除) #### 6. 解决常见问题 1. **路径问题**:打包后文件路径会改变,使用以下方法获取正确路径: ```python import sys import os if getattr(sys, 'frozen', False): base_path = sys._MEIPASS # 打包后路径 else: base_path = os.path.dirname(__file__) ``` 2. **资源文件打包**: ```bash pyinstaller --add-data "source;destination" your_script.py ``` 例如:`--add-data "images/*.png;images"` 3. **减小exe体积**: - 使用虚拟环境安装最小依赖 - 添加UPX压缩(下载UPX后使用`--upx-dir`参数) #### 7. 高级技巧 1. **添加版本信息**: 创建`version.txt`文件: ``` # UTF-8 VSVersionInfo( ffi=FixedFileInfo(...), kids=[ StringFileInfo(...), VarFileInfo(...) ] ) ``` 打包命令: ```bash pyinstaller --version-file version.txt your_script.py ``` 2. **多平台打包**: - Windows下打包:生成`.exe` - Linux下打包:生成可执行文件 - macOS下打包:生成`.app` > 注意:打包过程中会生成.spec文件,可手动编辑该文件进行高级配置[^1][^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值