py2exe打包python文件成可執行程序

py2exe打包主要分爲兩大類:

(1)、普通python腳本程序打包,不包含圖形界面庫。此類程序打包我用了兩種方法:

           方法一、比較常見,網上大多用這種方法。代碼實例如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#  py2exe file
# 1.install py2exe application
# 2.python setup.py py2exe
from distutils.core import setup
import py2exe,sys,os
includes = ["encodings", "encodings.*"]

origIsSystemDLL = py2exe.build_exe.isSystemDLL
def isSystemDLL(pathname):
        return origIsSystemDLL(pathname)
py2exe.build_exe.isSystemDLL = isSystemDLL

setup(console=[{'script':'DbCopy.py','icon_resources':[(1,"icon.ico")]}],
       options={'py2exe': {'includes':['sip','ConfigParser','pymssql','cx_Oracle','decimal'],
                "optimize": 0,
                "includes": includes
                #,"bundle_files": 1
                          }},
       data_files=["icon.ico"])

方法二、

# -*- coding: utf-8-*-
from distutils.core import setup
from glob import glob 
import py2exe
import os, sys
import shutil

if len(sys.argv) == 1:
    sys.argv.append("py2exe")
   
includes = ["encodings", "encodings.*"] 
options = {"py2exe": 
             {   "compressed": 1, 
                 "optimize": 2, 
                 "includes": includes, 
   "dist_dir": "bin",
                 "bundle_files": 1 
             } 
           } 
setup(    
     version = "0.1", 
     description = u'runexe', 
     name = "runexe", 
     options = options, 
     zipfile = None, 
     console=[{"script": "runexe.py"}],   
     )
os.remove("bin//w9xpopen.exe")    
shutil.rmtree("build")

以上兩種方法基本一樣,只是寫法有點不同,用法也有點不同,

前面一種比較零活,適合用了多個驅動包的程序。後一種適合比較純的python腳本,拿來改一下要打包的文件名就可以了。

(例如:我在用python連接mssql的時候,第二種方法一直沒成功,後來用第一中方法很快解決了,但是我習慣用第二種)

(2)、包含圖形界面(pyqt)的程序打包

#setup.py

# -*- coding: utf-8-*-

from distutils.core import setup
import py2exe,sys,os
includes = ["encodings", "encodings.*"]

origIsSystemDLL = py2exe.build_exe.isSystemDLL
def isSystemDLL(pathname):
        if os.path.basename(pathname).lower() in ("QtSvg4.dll"):
                return 0
        return origIsSystemDLL(pathname)
py2exe.build_exe.isSystemDLL = isSystemDLL

setup(windows=[{'script':'RunManager.py','icon_resources':[(1,"icon.ico")]}],
       options={'py2exe': {'includes':['sip','PyQt4._qt','PyQt4.QtCore','PyQt4.QtSvg','PyQwt'],
                "optimize": 0,
                "includes": includes
                #,"bundle_files": 1
                          }},
      data_files=["icon.ico"])

 

以下是操作步驟:

1、Dos窗口進入本目錄
2、運行命令 python setup.py py2exe --includes PyQt4.QtSvg,sip
3、生成文件在dist目錄
4、需要手動拷貝到dist目錄的文件:images(目錄);app.init;打包相關文件中的PyQt4、qt.conf、QtSvg4.dll;

發佈了68 篇原創文章 · 獲贊 6 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章