最新消息:

用PyInstaller把Python代码打包成exe可执行文件

Python admin 6760浏览 0评论

一、安装

下载地址:http://www.pyinstaller.org/。下载完成解压后,直接运行python setup.py install来安装就可以了。(可能需要安装pywin32模块:https://github.com/mhammond/pywin32/releases)

—————————————————————————————————————————————————-

参考在线文档:

http://www.pyinstaller.org/export/v2.0/project/doc/Manual.html?format=raw

Installing PyInstaller

如果安装时说需要PyWin32,那么得先去装这个。【已解决】Python中出错:ImportError: No module named win32com.client

但是要注意的是,import不是pywin32,而是win32com:

Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pywin32
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pywin32
>>> import win32com
>>>

 

———————————————————————————————————————————————-

二、使用

生成exe需要的是pyinstaller.py程序。使用帮助如下:

Usage: pyinstaller.py [opts] <scriptname> [ <scriptname> ...] | <specfile>

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:
                        D:\PyInstaller-2.1\PyInstaller-2.1\dist)
  --workpath=WORKPATH   Where to put all the temporary work files, .log, .pyz
                        and etc. (default:
                        D:\PyInstaller-2.1\PyInstaller-2.1\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=LOGLEVEL  Amount of detail in build-time console messages
                        (default: INFO, choose one of DEBUG, INFO, WARN,
                        ERROR, CRITICAL)

  What to generate:
    -F, --onefile       Create a one-file bundled executable.
    -D, --onedir        Create a one-folder bundle containing an executable
                        (default)
    --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
                        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.

  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 F
ILE.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 FILE[,TYPE[,NAME[,LANGUAGE]]], --resource=FILE[,TYPE[,NAME[,LANGUAGE]]]
                        Add or update a resource of the given type, name and
                        language from FILE to a Windows executable. 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.

  Obsolete options (not used anymore):
    -X, -K, -C, -o, --upx, --tk, --configfile, --skip-configure, --out, --buildp
ath
                        These options do not exist anymore.

 

平时需要使用的几个参数是:

    What to generate:

    -F, --onefile

    create a single file deployment

    -D, --onedir

    create a single directory deployment (default)

    -o DIR, --out=DIR

    create the spec file in directory. If not specified, and the current directory is Installer’s root directory, an output subdirectory will be created. Otherwise the current directory is used.

    -n NAME, --name=NAME

    optional name to assign to the project (from which the spec file name is generated). If omitted, the basename of the (first) script is used.

即使用-F参数可以只生成一个可执行文件。具体的使用过程如下:

(1)准备好要生成exe的py文件,要确保python文件能够正常执行。

我这里用的是wordpress的插件枚举代码,放在了pyinstaller.py目录下的wp目录中:

20140805221833

(2)执行命令python pyinstaller.py ./wp/wp_plugin.py 来生成exe

20140805222655

可以看到在pyinstaller目录下已经生成与py文件名相同的文件夹,在文件夹下有生成的exe文件。该exe可以成功执行,不过看到除了exe还生成了许多pyd文件。如果我们要想生成的文件尽可能少,需要使用-F参数。

(3)删掉生成的exe等文件。执行命令python pyinstaller.py ./wp/wp_plugin.py -F 来生成单个exe文件

20140806100538

20140806100625

可以看到只生成了一个exe文件。

ps:在生成的过程中没有遇到找不到模块的问题,如果在生成过程中遇到找不到自己编写的库的问题,可以使用-p参数来添加扫描路径。

    -p DIR, --paths=DIR

    set base path for import (like using PYTHONPATH). Multiple directories are allowed, separating them with the path separator (‘;’ under Windows, ‘:’ under Linux), or using this option multiple times.

其他情况如程序添加图标使用-i参数,其他就参考:http://www.crifan.com/use_pyinstaller_to_package_python_to_single_executable_exe/来解决吧。

总结:

1、生成单一的exe文件: -F

python pyinstaller.py ./wp/wp_plugin.py  -F

2、添加必要的模块搜索路径 -p

python pyinstaller.py -p D:\tmp\;D:\lib\; ./wp/wp_plugin.py  -F

3、带图标 -i

python pyinstaller.py -i E:\favicon.ico  ./wp/wp_plugin.py  -F

20140806100625

另外pyinstaller支持upx压缩,暂时没有去研究。

UPX是一款先进的可执行程序文件压缩器。压缩过的可执行文件体积缩小50%-70% ,这样减少了磁盘占用空间、网络上传下载的时间和其它分布以及存储费用。 通过 UPX 压缩过的程序和程序库完全没有功能损失,和压缩之前一样可正常地运行。对于支持的大多数格式没有运行时间或内存的不利后果。
UPX 支持许多不同的可执行文件格式 :包含 Windows 95/98/ME/NT/2000/XP/CE 程序和动态链接库、DOS 程序、Linux 可执行文件和核心。
UPX有不光彩的使用记录,它被用来给木马和病毒加壳,躲避杀毒软件的查杀。
UPX是一个著名的压缩壳,主要功能是压缩PE文件(比如exe,dll等文件),有时候也可能被病毒用于免杀.壳upx是一种保护程序。一般是EXE文件的一种外保护措施,主要用途 :
1、让正规文件被保护起来,不容易被修改和破解。
2、使文件压缩变小。
3、保护杀毒软件安装程序,使之不受病毒侵害。
4、木马,病毒的保护外壳,使之难以为攻破。 仅仅看一个壳upx路径 是不能确定什么的。要仔细看看他相对应的文件,如果是杀毒或者是自己已知的文件那就无伤大雅,要是其他疑似,就要认真对待了。
有些软件的安装程序是加壳安装的,属正常现象。 建议查杀一下恶意程序、病毒。

技术原理:对于可执行程序资源压缩,是保护文件的常用手段. 俗称加壳,加壳过的程序可以直接运行,但是不能查看源代码.要经过脱壳才可以查看源代码.
加壳:其实是利用特殊的算法,对EXE、DLL文件里的资源进行压缩。类似WINZIP 的效果,只不过这个压缩之后的文件,可以独立运行,解压过程完全隐蔽,都在内存中完成。解压原理,是加壳工具在文件头里加了一段指令,告诉CPU,怎么才能解压自己。当加壳时,其实就是给可执行的文件加上个外衣。用户执行的只是这个外壳程序。当执行这个程序的时候这个壳就会把原来的程序在内存中解开,解开后,以后的就交给真正的程序。

ps:PyInstaller打包遇到的问题是相对路径的问题,即在打包的exe中不能用__file__来获取exe执行的目录,需要使用sys.executable来获取exe执行时的路径。因此在需要打包的python程序中获取当前路径的代码如下:

    if getattr(sys, 'frozen', None):
        basedir = os.path.dirname(sys.executable)
    else:
        basedir = os.path.dirname(__file__)
    fiel_name = basedir+'\\QQWry.dat'

参考资料:

1、http://www.crifan.com/use_pyinstaller_to_package_python_to_single_executable_exe/

转载请注明:jinglingshu的博客 » 用PyInstaller把Python代码打包成exe可执行文件

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址