http://blog.csdn.net/pipisorry/article/details/50620122

Python不是每个人的计算机里面都有安装,当您写了一个好用的工具,需要一个standalone exectuable环境的需求。并且用python写些脚本什么的,有时候脚本写完以后,每次运行都得在IDE打开在运行,很麻烦,所以经常将python编译成exe。

本文介绍如何将一个python项目(或者简单一点一个python脚本文件)转化为windows下的可执行文件。

转化要使用python转换为exe可执行文件的库,一个是py2exe,另外一个就是PyInstaller。

py2exe:

打包好的exe只能在相同的系统下运行,比如你在XP系统用py2exe打包好的exe只能在XP上运行,在win7上肯定有问题,而且也是存在在别的XP机子上也可能不能运行,因为一些别的机子可能会缺少dll文件;

打包的文件也需要打包同exe下的dll,和一些库的压缩包,不然exe根本跑不起来

还需要另外的其他库文件配置。

PyInstaller:

可以只是生成单独的可执行程序

且支持的版本也多:2.3到2.7都支持。以及x64也支持

也可以自定义图标

本文介绍pyinstaller的使用。

安装pyinstaller

pyinstaller支持python2和python3

命令行安装:pip install pyinstaller

或者去下载安装:PyInstaller 3.1 (tar.gz) | http://sourceforge.net/projects/pywin32/files/pywin32/Build%20217/

Note: windows下转换要先安装pywin32:  pip install pywin32[pywin32的安装]

皮皮blog

pyinstaller的使用

命令行中转换py文件为exe文件

pi@PIPI /e/mine/python_workspace/nlp(dev)

$pyinstaller -F E:/mine/python_workspace/NLP/TargetOpinion/TargetOpinionMain.py

在命令行当前路径/e/mine/python_workspace/nlp中会生成

dist目录(目录里面有可执行文件)

build目录(生成exe的中间文件)

spec文件(要转换文件的同一目录下,用于生成exe文件,可以修改来自定义生成exe的属性)

指定dist生成目录路径(而不是命令行当前目录)

pyinstaller -F E:/mine/python_workspace/test0/testMain.py --distpath=E:/mine/python_workspace/test0/dist

压缩生成的exe文件

用UPX去压缩,压缩后所生成的exe文件的大小,会小得多

--upx        I mentioned that this is a great option, and it is, but it's really slow, especially as your source file gets bigger.  It's a great option for your final compile before distributing,
but you might save a lot of time if you turn it off until then.

先下载http://upx.sourceforge.net/解压到要转换到的py文件目录下

pyinstaller参数中添加upx路径

pyinstaller -F E:/mine/python_workspace/NLP/TargetOpinion/TargetOpinionMain.py--upx-dir upx391w

[http://pythonhosted.org/PyInstaller/#using-upx]

直接进入界面程序

pyinstaller生成的exe文件是从命令行开始执行的,如果之前的程序是界面程序(如pyqt界面开始执行的),则要改成从界面执行,这样就不会看到命令行输出了(如bug错误输出、print输出等)

pyinstaller -Fw E:/mine/python_workspace/NLP/TargetOpinion/TargetOpinionMain.py

当然,如果是在调试期间,建议不要加w参数,这样就可以从命令行看到bug提示了。

修改中间文件spec文件生成自定义exe文件

修改中间文件,再去生成exe文件

如,在生成exe文件的同时,在exe目录下(dist目录)生成一个数据文件,相当于将python项目中的数据文件拷贝到dist目录

修改spec文件中datas如下:datas= [ ('nlptest/patternFile.txt', '.' ) ],

pyinstaller -F E:/mine/python_workspace/test0/testMain.spec

[http://pythonhosted.org/PyInstaller/#using-spec-files]

一步一步生成

当然也可以一步一步生成,并使用中间文件

生成中间文件:python Makespec.py --console --onefile NotePad\notepad.py

再build生成exe文件:python Build.py NotePad\notepad.spec

[关于python打包成exe的一点经验之谈]

[.py程序转换成.exe可执行程序]

py代码调用pyinstaller,将.py文件转换成exe文件(推荐)

当然也可以在TargetOpinionMain.py同目录下创建一个转换文件TargetPy2exe.py:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = '将TargetOpinionMain python项目转换为exe文件'
__author__ = '皮'
__email__ = 'pipisorry@126.com'
"""
from PyInstaller.__main__ import run

if __name__ == '__main__':
    opts = ['TargetOpinionMain.py', '-F']
    # opts = ['TargetOpinionMain.py', '-F', '-w']
    # opts = ['TargetOpinionMain.py', '-F', '-w', '--icon=TargetOpinionMain.ico','--upx-dir','upx391w']
    run(opts)

效果同命令行执行是一样的,只不过使用IDE执行这个转换代码,出错的话会有出错栈提示,可以很快到达出错位置;并且生成的build、dist目录就在本目录下,不用担心在命令行中执行目录错乱,找不到或者搞混dist目录。

pyinstaller生成exe文件后,数据文件读取路径的改变

python项目中读取文件会出错,其原因是读取的文件路径不是原来的了,因为所有文件都编译了,成了一个文件exe文件。

文件目录的改变可参考:[pyinstaller 生成单一的EXE文件之后获取当前目录的方法]

如果pythony代码中有读取文件操作,解决方案见:[pyinstaller相关错误]

皮皮blog

附录

pyinstaller参数

General Options

-h, --help show this help message and exit
-v, --version Show program version info and exit.
--distpath DIR Where to put the bundled app (default: ./dist)
--workpath WORKPATH
  Where to put all the temporary work files, .log, .pyz and etc. (default: ./build)
-y, --noconfirm
  Replace output directory (default: SPECPATH/dist/SPECNAME) without asking for confirmation
--upx-dir UPX_DIR
  Path to UPX utility (default: search the execution path)
-a, --ascii Do not include unicode encoding support (default: included if available)
--clean Clean PyInstaller cache and remove temporary files before building.
--log-level LEVEL
  Amount of detail in build-time console messages. LEVEL may be one of DEBUG, INFO, WARN, ERROR, CRITICAL (default: INFO).

What to generate

-D, --onedir Create a one-folder bundle containing an executable (default)
-F, --onefile Create a one-file bundled executable.
--specpath DIR Folder to store the generated spec file (default: current directory)
-n NAME, --name NAME
  Name to assign to the bundled app and spec file (default: first script's basename)

What to bundle, where to search

-p DIR, --paths DIR
  A path to search for imports (like using PYTHONPATH). Multiple paths are allowed, separated by ':', or use this option multiple times
--hidden-import MODULENAME, --hiddenimport MODULENAME
  Name an import not visible in the code of the script(s). This option can be used multiple times.
--additional-hooks-dir HOOKSPATH
  An additional path to search for hooks. This option can be used multiple times.
--runtime-hook RUNTIME_HOOKS
  Path to a custom runtime hook file. A runtime hook is code that is bundled with the executable and is executed before any other code or module to set up special features of the runtime environment. This option can be used multiple times.
--exclude-module EXCLUDES
  Optional module or package (his Python names, not path names) that will be ignored (as though it was not found). This option can be used multiple times.
--key KEY The key used to encrypt Python bytecode.

How to generate

-d, --debug Tell the bootloader to issue progress messages while initializing and starting the bundled app. Used to diagnose problems with missing imports.
-s, --strip Apply a symbol-table strip to the executable and shared libs (not recommended for Windows)
--noupx Do not use UPX even if it is available (works differently between Windows and *nix)

Windows and Mac OS X specific options

-c, --console, --nowindowed
  Open a console window for standard i/o (default)
-w, --windowed, --noconsole
  Windows and Mac OS X: do not provide a console window for standard i/o. On Mac OS X this also triggers building an OS X .app bundle. This option is ignored in *NIX systems.
-i <FILE.ico or FILE.exe,ID or FILE.icns>, --icon <FILE.ico or FILE.exe,ID or FILE.icns>
  FILE.ico: apply that icon to a Windows executable. FILE.exe,ID, extract the icon with ID from an exe. FILE.icns: apply the icon to the .app bundle on Mac OS X

Windows specific options

--version-file FILE
  add a version resource from FILE to the exe
-m <FILE or XML>, --manifest <FILE or XML>
  add manifest FILE or XML to the exe
-r RESOURCE, --resource RESOURCE
  Add or update a resource to a Windows executable. The RESOURCE is one to four items, FILE[,TYPE[,NAME[,LANGUAGE]]]. FILE can be a data file or an exe/dll. For data files, at least TYPE and NAME must be specified. LANGUAGE defaults to 0 or may be specified as
wildcard * to update all resources of the given TYPE and NAME. For exe/dll files, all resources from FILE will be added/updated to the final executable if TYPE, NAME and LANGUAGE are omitted or specified as wildcard *.This option can be used multiple times.
--uac-admin Using this option creates a Manifest which will request elevation upon application restart.
--uac-uiaccess Using this option allows an elevated application to work with Remote Desktop.

Windows Side-by-side Assembly searching options (advanced)

--win-private-assemblies
  Any Shared Assemblies bundled into the application will be changed into Private Assemblies. This means the exact versions of these assemblies will always be used, and any newer versions installed on user machines at the system level will be ignored.
--win-no-prefer-redirects
  While searching for Shared or Private Assemblies to bundle into the application, PyInstaller will prefer not to follow policies that redirect to newer versions, and will try to bundle the exact versions of the assembly.

Mac OS X specific options

--osx-bundle-identifier BUNDLE_IDENTIFIER
  Mac OS X .app bundle identifier is used as the default unique program name for code signing purposes. The usual form is a hierarchical name in reverse DNS notation. For example: com.mycompany.department.appname (default: first script's basename)

Shortening the Command

Because of its numerous options, a full pyinstaller command can become very long. You will run the same command again and again as you develop
your script. You can put the command in a shell script or batch file, using line continuations to make it readable. For example, in Linux:

pyinstaller --noconfirm --log-level=WARN \
    --onefile --nowindow \
    --hidden-import=secret1 \
    --hidden-import=secret2 \
    --upx-dir=/usr/local/share/ \
    myscript.spec

Or in Windows, use the little-known BAT file line continuation:

pyinstaller --noconfirm --log-level=WARN ^
    --onefile --nowindow ^
    --hidden-import=secret1 ^
    --hidden-import=secret2 ^
    --icon-file=..\MLNMFLCN.ICO ^
    myscript.spec

[http://pythonhosted.org/PyInstaller/#options]

pyinstaller-2.0 参数(翻译)

Note:--onefile前面是两个-。

-F    制作独立的可执行程序

-D    制作出的档案存放在同一个文件夹下(默认值)

-K    包含TCL/TK(对于使用了TK的,最好加上这个选项,否则在未安装TK的电脑上无法运行)

-w     制作窗口程序

-c    制作命令行程序(默认)

-X    制作使用UPX压缩过的可执行程序(推荐使用这个选项,需要下载UPX包,解压后upx.exe放在Python(非PyInstaller)安装目录下,下载upx308w.zip)

-o DIR  指定输出SPEC文件路径(这也决定了最后输出的exe文件路径)

--icon=[ICO文件路径] 指定程序图标

-v [指定文件] 指定程序版本信息

-n [指定程序名] 指定程序名称

pyinstaller生成的exe文件执行过程

单独生成一个exe文件(-F参数)后,exe文件是怎么运行的:

How the One-File Program Works

The bootloader is the heart of the one-file bundle also. When started it creates a temporary folder in the appropriate temp-folder location for this OS. The folder is named _MEIxxxxxx, where xxxxxx is a random number.

The one executable file contains an embedded archive of all the Python modules used by your script, as well as compressed copies of any non-Python support files (e.g. .so files). The bootloader uncompresses the support files and writes copies into the the temporary
folder. This can take a little time. That is why a one-file app is a little slower to start than a one-folder app.

After creating the temporary folder, the bootloader proceeds exactly as for the one-folder bundle, in the context of the temporary folder. When the bundled code terminates, the bootloader deletes the temporary folder.

[http://pythonhosted.org/PyInstaller/#how-the-one-file-program-works]

What happens during execution of bootloader:

  1. First process: bootloader starts.

    1. If one-file mode, extract bundled files to temppath_MEIxxxxxx
    2. Set/unset various environment variables, e.g. override LD_LIBRARY_PATH on Linux or LIBPATH on AIX; unset DYLD_LIBRARY_PATH on OSX.
    3. Set up to handle signals for both processes.
    4. Run the child process.
    5. Wait for the child process to finish.
    6. If one-file mode, delete temppath_MEIxxxxxx.注意,exe文件运行完成后,temp目录下的临时文件_mei***就会被删除。
  2. Second process: bootloader itself started as a child process.

    1. On Windows set the activation context.
    2. Load the Python dynamic library. The name of the dynamic library is embedded in the executable file.
    3. Initialize Python interpreter: set sys.path, sys.prefix, sys.executable.
    4. Run python code.

Running Python code requires several steps:

  1. Run the Python initialization code which prepares everything for running the user's main script. The initialization code can use only the Python built-in modules because the general import mechanism is not yet available. It sets up the Python import mechanism
    to load modules only from archives embedded in the executable. It also adds the attributes frozen and _MEIPASS to
    the sys built-in module.
  2. Execute any run-time hooks: first those specified by the user, then any standard ones.
  3. Install python "egg" files. When a module is part of a zip file (.egg), it has been bundled into the ./eggs directory. Installing means appending
    .egg file names to sys.path. Python automatically detects whether an item in sys.path is
    a zip file or a directory.
  4. Run the main script.

[http://pythonhosted.org/PyInstaller/#bootloader]

py2exe使用参考

[http://www.py2exe.org/index.cgi/Tutorial]

from:http://blog.csdn.net/pipisorry/article/details/50620122

ref:Simple guide to using PyInstaller

PyInstaller Manual*

pyinstaller使用-python项目转换成exe可执行文件的更多相关文章

  1. 将Python项目打包成EXE可执行文件(单文件,多文件,包含图片)

    解决 将Python项目打包成EXE可执行文件(单文件,多文件,包含图片) 1.当我们写了一个Python的项目时,特别是一个GUI项目,我们特备希望它能成为一个在Windows系统可执行的EXE文件 ...

  2. 使用py2exe将python脚本转换成exe可执行文件

    Python(wiki en  chs)是一门弱类型解释型脚本语言,拥有动态类型系统和垃圾回收功能,支持多种编程范式:面向对象.命令式.函数式和过程式编程. 由于Python拥有一个巨大而广泛的标准库 ...

  3. 用pyinstaller把python代码打包成exe可执行文件

    优点: 1. pyinstaller 是跨平台的可以用在linux和windows系统上 2. 操作非常简单,几个命令就搞定了,这个比py2exe容易用多了 缺点: 1. 打包后的体积过大,因为要带p ...

  4. windows下使用pyinstaller把python文件打包成exe可执行文件

    使用pyinstaller打包有个好处就是所有依赖都打包进去了,可以随意把文件移动到别的电脑上使用 安装 pip install pyinstaller 新建一个demo.py文件 #!/usr/bi ...

  5. PyQt(Python+Qt)学习随笔:windows下使用pyinstaller将PyQt文件打包成exe可执行文件

    专栏:Python基础教程目录 专栏:使用PyQt开发图形界面Python应用 专栏:PyQt入门学习 老猿Python博文目录 在<windows下使用pyinstaller将多个目录的Pyt ...

  6. 将Python脚本封装成exe可执行文件 转

    将Python脚本封装成exe可执行文件 http://www.cnblogs.com/renzo/archive/2012/01/01/2309260.html  cx_freeze是用来将 Pyt ...

  7. 将jar文件转换成exe可执行文件[转]

    将jar文件转换成exe可执行文件: exe文件使用方便,而且还可以提高源码及资源的安全性,但同时也失去了java的初衷--跨平台性. 如果你坚持要转换成exe文件,请按以下方式进行: 利用exe4j ...

  8. 小白学习Python之路---py文件转换成exe可执行文件

    一.背景 今天闲着无事,写了一个小小的Python脚本程序,然后给同学炫耀的时候,发现每次都得拉着其他人过来看着自己的电脑屏幕,感觉不是很爽,然后我想着网上肯定有关于Python脚本转换成可执行文件的 ...

  9. Python 程序打包成 exe 可执行文件

    Python 程序打包工具 Python 是一个脚本语言,被解释器解释执行.它的发布方式: .py 文件:对于开源项目或者源码没那么重要的,直接提供源码,需要使用者自行安装 Python 并且安装依赖 ...

随机推荐

  1. Delphi 打印 Tprinter

    打印          打印对于许多 Windows 程序员来说是十分棘手的问题. Delphi 简化了打印时用户所必须了解的大部分内容.用户可以很轻松地写出简单的打印程序来输出文本和位图化了的图像. ...

  2. Python中def及lambda的功能介绍

    函数def及lambda的功能介绍 1. def函数的功能介绍 1. 函数的参数 无参数函数 格式:def func_name(): '''__doc__'''#函数的说明文档(内容) express ...

  3. 阿里Java研发工程师实习面经

    十分幸运 拿到阿里云的offer,感谢周围无数人对我的支持和鼓励,所以写篇面经希望可以帮助大家. 面试中,运气占很大一部分的,所以你们若是没有通过,一定不要气馁,继续加油. 每个努力的人 都值得钦佩, ...

  4. java中JSON转换

    1.JSON介绍 JSON是一种取代XML的数据结构,和xml相比,它更小巧但描述能力却不差,由于它的小巧所以网络传输数据将减少更多流量从而加快速度. JSON就是一串字符串 只不过元素会使用特定的符 ...

  5. PWA初体验

    一.前言 现在市面上的Native  APP成千上万个,各种应用商店里面的APP琳琅满目.原生的APP下载到手机上之后,用户就可以获取一个方便的入口,体验上也十分顺畅.但是再好的事物难免有点缺点: 1 ...

  6. 浅谈Log4net在项目中如何记录日志

    一    引入背景 在软件开发周期中,无论是开发中,或是测试中,或是上线后,选择合适的工具监控程序的运行状态至关重要,只有如此,才能更好地排查程序问题和检测程序性能问题等.本篇文章主要与大家分享,如何 ...

  7. Day 1 Python简单程序

    一.高级语言和低级语言   最初的计算机程序都是用0和1的序列表示的,程序员直接使用的是机器指令,无需翻译,从纸带打孔输入即可执行得到结果.后来为了方便记忆,就将用0.1序列表示的机器指令都用符号助记 ...

  8. 【python标准库模块五】Xml模块学习

    Xml模块 xml本身是一种格式规范,是一种包含了数据以及数据说明的文本格式规范.在json没有兴起之前各行各业进行数据交换的时候用的就是这个.目前在金融行业也在广泛在运用. 举个简单的例子,xml是 ...

  9. PHP 文件

    PHP 文件处理 fopen() 函数用于在 PHP 中打开文件. 打开文件 fopen() 函数用于在 PHP 中打开文件. 此函数的第一个参数含有要打开的文件的名称,第二个参数规定了使用哪种模式来 ...

  10. Template基础

    模板系统的介绍 你可能已经注意到我们在例子视图中返回文本的方式有点特别. 也就是说,HTML被直接硬编码在 Python代码之中. def current_datetime(request): now ...