打包python脚本为exe可执行文件-pyinstaller和cx_freeze示例

本文介绍使用cx_freezepyinstaller打包python脚本为exe文件

cx_freeze的使用实例

需要使用到的文件wxapp.py, read_file.py, setup.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#file: wxapp.py

import wx
import os
import sys
import read_file


class Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, parent=None, title='Hello from cx_Freeze')
        panel = wx.Panel(self)
        closeMeButton = wx.Button(panel, -1, 'Close Me')
        wx.EVT_BUTTON(self, closeMeButton.GetId(), self.OnCloseMe)
        wx.EVT_CLOSE(self, self.OnCloseWindow)
        pushMeButton = wx.Button(panel, -1, 'Push Me')
        wx.EVT_BUTTON(self, pushMeButton.GetId(), self.OnPushMe)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(closeMeButton, flag=wx.ALL, border=20)
        sizer.Add(pushMeButton, flag=wx.ALL, border=20)
        panel.SetSizer(sizer)
        topSizer = wx.BoxSizer(wx.VERTICAL)
        topSizer.Add(panel, flag=wx.ALL | wx.EXPAND)
        topSizer.Fit(self)

    def OnCloseMe(self, event):
        obj = read_file.PrintContent()
        if getattr(sys, 'frozen', None):
            path = os.path.dirname(sys.executable)
        else:
            path = os.path.dirname(__file__)
        path = os.path.join(path, "read_file.py")
        obj.show_content(path)

    def OnPushMe(self, event):
        wx.MessageBox('I was pushed!', 'Informational message')

    def OnCloseWindow(self, event):
        self.Destroy()


class App(wx.App):
    def OnInit(self):
        frame = Frame()
        frame.Show(True)
        self.SetTopWindow(frame)
        return True


app = App(1)
app.MainLoop()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#file: read_file.py

class PrintContent(object):
    def show_content(self, path):
        f = open(path)
        for line in f:
            print line
        f.close()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#file: setup.py

# A simple setup script to create an executable running wxPython. This also
# demonstrates the method for creating a Windows executable that does not have
# an associated console.
#
# wxapp.py is a very simple 'Hello, world' type wxPython application
#
# Run the build process by running the command 'python setup.py build'
#
# If everything works well you should find a subdirectory in the build
# subdirectory that contains the files needed to run the application
import sys
from cx_Freeze import setup, Executable

build_exe_options = {"optimize": 2,
                     "include_files": ["read_file.py"]}

base = None
if sys.platform == 'win32':
    base = 'Win32GUI'

executables = [Executable(script='wxapp.py',
               base=base,
               targetName="Demo.exe",
               compress=True,
               icon="py.ico")]

setup(name='wxapp',
      version='0.1',
      description='Sample cx_Freeze wxPython script',
      options = {"build_exe": build_exe_options},
      executables=executables)

打开cmd进入代码所在目录,然后输入:

cx_freeze

然后会生成build和dist两个文件夹,build文件夹里存放的是exe可执行文件和所依赖的库,直接把整个文件夹复制给别人就可以通过双击exe文件运行了,dist文件夹下是build文件夹的安装程序,直接传dist文件夹下的安装包给朋友,朋友运行安装包后会得到和build一样的文件夹,路径由用户自己选择

至于setup.py里面的参数选项可以自己去官网查看相应的选项信息


pyinstaller的使用实例

pyinstaller中使用到的文件wxapp.py, file_read.py, wxapp.spec 前两个文件和上面的内容相同

# -*- mode: python -*-
#file: wxapp.spec
#convert the path('E:\book\code\python\wx\') to your file path
a = Analysis(['E:\book\code\python\wx\wxapp.py',
             'E:\book\code\python\wx\read_file.py'],
             pathex=['E:\book\code\python\wx'],
             hiddenimports=[],
             hookspath=None,
             runtime_hooks=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name=os.path.join('dist', 'Demo.exe'),
          debug=False,
          strip=None,
          upx=True,
          console=False,
          icon='D:\PyInstaller-2.1\xrced.ico')
collect = COLLECT(exe,
                  [("read_file.py", r"E:ookcodepythonwx
ead_file.py", "DATA")],
                  name="dist")

打开cmd,切换到pyinstaller的目录,然后输入如下的命令:

python pyinstaller.py path_of_spec   (PS:这里的path_of_spec 替换为你保存的wxapp.spec的绝对路径,可以直接拖拽到cmd中得到路径哦^_^

我这里使用了upx进行压缩,你也可以不使用,具体使用方法见官网说明

执行完成之后会生成wxapp文件夹,wxapp/dist/dist里Demo.exe和read_file.py就是你所需要的文件了


至此,cx_freeze和pyinstaller的两种打包方式就介绍完了,我个人比较喜欢pyinstaller,定制性强、自动搜索模块依赖、可以生成单独的exe文件、官方文档给的详细,缺点不支持py3.x ,但是现在绝大多数都是py2.x的天下。。。

我相信在不久py3.x开始流行的时候pyinstaller会跟进的


2014年1月23日20:03:36更新

对于pyinstaller的使用更新,今天重新阅读了下官网给出的说明文档,对于spec文件可以使用工具自动生成一个,命令:

pyi-makespec webapp.py file_read.py

这样会生成一个wxapp.spec的文件,然后可以在这个文件的基础上进行修改,这里我只提几点需要注意的事项在EXE的选项中exclude_binaries控制是否打包为单独的exe文件,还有一点需要注意如果你的软件需要读写一个配置文件,且这个配置文件跟app在同级目录下,那么在你的py文件中需要这样来引用这个配置文件的路径: BASEDIR = os.path.dirname(__file__) 来获取配置文件,然后使用 CONFIG_PATH = os.path.join(BASEDIR, 'config.ini')来制定配置文件的路径.其他没啥需要注意的了

 修改完spec文件之后可以使用以下的命令生成exe文件:

pyi-build wxapp.spec --upx-dir=dir_path_of_upx

作者:msccreater

转载请注明出处:http://www.cnblogs.com/msccreater/p/3530250.html

原文地址:https://www.cnblogs.com/msccreater/p/3530250.html