打包python腳本爲exe可執行文件-pyinstaller和cx_freeze示例

本文介紹使用cx_freezepyinstaller打包python腳本爲exe文件html

cx_freeze的使用實例

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

#!/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進入代碼所在目錄,而後輸入:web

cx_freeze

而後會生成build和dist兩個文件夾,build文件夾裏存放的是exe可執行文件和所依賴的庫,直接把整個文件夾複製給別人就能夠經過雙擊exe文件運行了,dist文件夾下是build文件夾的安裝程序,直接傳dist文件夾下的安裝包給朋友,朋友運行安裝包後會獲得和build同樣的文件夾,路徑由用戶本身選擇app

至於setup.py裏面的參數選項能夠本身去官網查看相應的選項信息webapp

 


 

 

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:\book\code\python\wx\read_file.py", "DATA")],
                  name="dist")

打開cmd,切換到pyinstaller的目錄,而後輸入以下的命令:oop

python pyinstaller.py path_of_spec   (PS:這裏的path_of_spec 替換爲你保存的wxapp.spec的絕對路徑,能夠直接拖拽到cmd中獲得路徑哦^_^

我這裏使用了upx進行壓縮,你也能夠不使用,具體使用方法見官網說明ui

執行完成以後會生成wxapp文件夾,wxapp/dist/dist裏Demo.exe和read_file.py就是你所須要的文件了spa

 


至此,cx_freeze和pyinstaller的兩種打包方式就介紹完了,我我的比較喜歡pyinstaller,定製性強、自動搜索模塊依賴、能夠生成單獨的exe文件、官方文檔給的詳細,缺點不支持py3.x ,可是如今絕大多數都是py2.x的天下。。。.net

我相信在不久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

相關文章
相關標籤/搜索