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

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

本文介绍使用cx_freeze和pyinstaller打包python脚本为exe文件

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

#!/usr/bin/env python#-*- coding: utf-8 -*-#file: wxapp.pyimportwximportosimportsysimportread_fileclassFrame(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)defOnCloseMe(self, event):

obj=read_file.PRintContent()ifgetattr(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)defOnPushMe(self, event):

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

self.Destroy()classApp(wx.App):defOnInit(self):

frame=Frame()

frame.Show(True)

self.SetTopWindow(frame)returnTrue

app= App(1)

app.MainLoop()

#!/usr/bin/env python#-*- coding: utf-8 -*-#file: read_file.pyclassPrintContent(object):defshow_content(self, path):

f=open(path)forlineinf:printline

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 wxPythonapplication#

#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 applicationimportsysfromcx_Freezeimportsetup, Executable

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

base=Noneifsys.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进入代码所在目录,然后输入:

然后会生成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 patha = 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:\book\code\python\wx\read_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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航