Python封裝成可帶參數的EXE安裝包實例

今天小編就爲大家分享一篇Python封裝成可帶參數的EXE安裝包實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

最近有一個小項目,有如下的需求:

將某幾個源碼文件夾進行打包,文件夾內有py文件、dll文件、exe文件等各種文件類型

打包生成的安裝包,在進行安裝的時候,應該能夠帶有參數,對配置文件進行修改配置

安裝過程中,可以配置系統環境變量

能夠檢測環境,提示安裝依賴包

整個過程要可以自動化,能夠大量部署

綜合考慮後,決定以下幾個步驟完成:

用setup.py將源碼文件夾都打包成msi安裝包,這樣可以使用msiexec進行靜默安裝

setup.py可以提示用戶安裝依賴包,否則安裝失敗

再編寫一個py文件,用來靜默安裝msi安裝包,並配置系統環境變量,接受安裝參數去修改配置文件的屬性

最後使用pyinstaller將所有都打包成exe文件

先來編寫setup.py文件:

# coding=utf-8
from distutils.core import setup
import os
 
 
def get_all_dir(path):
  """
    獲取指定路徑下的所有文件
  """
  all_file = []
  for dirpath, dirnames, filenames in os.walk(path):
    for filename in filenames:
      all_file.append(dirpath)
  return all_file
 
 
if __name__ == '__main__':
  all_file = get_all_dir('A') + get_all_dir('B') # 獲取相對路徑下A和B兩個文件夾下的所有文件
  setup(name='Example', # 所要安裝的軟件名
     version="1.0", # 版本
     description="This is example", # 對所安裝軟件的描述
     author="author", # 作者
     author_email='my email', # 郵箱
     packages=all_file, # 要打包的文件
     package_data={'': ['*.*']}, # 所有文件類型都打包
     classifiers=[
       'Development Status :: 5 - Production/Stable',
       'Operating System :: Microsoft :: Windows',
       'Natural Language :: Chinese (Simplified)',
       'Programming Language :: Python',
       'Programming Language :: Python :: 2.7',
       'Topic :: Software Development :: Libraries :: Python Modules'
     ], # 需要參照https://pypi.python.org/pypi?%3Aaction=list_classifiers,用於發佈在PYPI上
     install_requires=[
       'pyserial==3.2.1'
     ], # 依賴包,如果沒有安裝,會提示缺少,並安裝失敗
     )

然後打開setup.py所在目錄,並將A和B兩個文件夾複製過來

打開dos窗口,並運行

python setup.py bdist_msi

運行結果如下圖:

build我們不關注,直接看dist,裏面有一個Example-1.0.win32.msi,這就是我們生成的msi安裝包。

我們再編寫一個Example.py用來配置系統環境變量,並接受安裝參數修改配置文件:

# coding=utf-8
import os
import sys
import subprocess
 
config_file = r"C:\Python27\Lib\site-packages\B\lib\configuration\config.cfg"
 
import sys
from subprocess import check_call
 
 
### 設置系統環境變量所需代碼
if sys.hexversion > 0x03000000:
  import winreg
else:
  import _winreg as winreg
 
ENV_VARAIABLE = 'Result_Path'
 
 
class Win32Environment:
  def __init__(self, scope):
    assert scope in ('user', 'system')
    self.scope = scope
    if scope == 'user':
      self.root = winreg.HKEY_CURRENT_USER
      self.subkey = 'Environment'
    else:
      self.root = winreg.HKEY_LOCAL_MACHINE
      self.subkey = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
 
  def getenv(self, name):
    key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_READ)
    try:
      value, _ = winreg.QueryValueEx(key, name)
    except WindowsError:
      value = ''
    return value
 
  def setenv(self, name, value):
    key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_ALL_ACCESS)
    winreg.SetValueEx(key, name, 0, winreg.REG_EXPAND_SZ, value)
    winreg.CloseKey(key)
    try:
      check_call('''\
  "%s" -c "import win32api, win32con; assert win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')"''' % sys.executable)
    except Exception as e:
      print e.message
 
 
### 設置系統環境變量所需代碼 end
 
 
def search_content(str, lists):
  """
    查找str是否存在於lists中,不存在就退出程序
  """
  for i in lists:
    if str in i:
      return lists.index(i)
  print "The section not found"
  os._exit(1)
 
 
def run_command_line(command_line):
  """
    運行command line
  """
  print("run:" + command_line)
  p = subprocess.Popen(command_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  (stdout, stderr) = p.communicate()
  try:
    print("stdout:" + stdout)
    print("stderr:" + stderr)
  except:
    pass
 
 
def main():
  # 靜默安裝MSI安裝包
  run_command_line("msiexec /i " + sys.path[0] + r"\Example-1.0.win32.msi /qb REBOOT=SUPPRESS")
 
  # 接受參數
  section = sys.argv[1]
  attribute = sys.argv[2]
  change = sys.argv[3]
 
  # 讀取配置文件內容
  file = open(config_file, 'r')
  content = file.readlines()
  file.close()
 
  # 修改配置文件的某個屬性值
  index = search_content(section, content)
  is_change = False
  for change_str in content[index + 1:]:
    if "[" in change_str:
      if not is_change:
        print "Property does not exist or not in this section"
      break
    if attribute in change_str:
      content[content.index(change_str)] = change_str[:change_str.index("=") + 1] + change + "\n"
      is_change = True
      break
 
  # 把修改後的內容寫入配置文件
  file = open(config_file, 'w')
  for i in content:
    file.write(i)
  file.close()
 
 
if __name__ == "__main__":
  # 如果沒有參數,就默認直接安裝MSI安裝包
  # 如果有參數,但是參數個數不足,直接報錯退出
  if len(sys.argv) == 1 and sys.argv[0] == "commonlib.exe":
    run_command_line("msiexec /i " + sys.path[0] + r"\Example-1.0.win32.msi /qb REBOOT=SUPPRESS")
  elif len(sys.argv) != 4:
    print "Usage: commonlib.py <section> <section-attribute> <attribute-value>"
    sys.exit(1)
  else:
    main()
 
  # 設置系統環境變量
  e = Win32Environment(scope="system")
  e.setenv(ENV_VARAIABLE, r'C:\Local')
  print "Setup Success!"

現在我們用Pyinstaller來進行最後的打包。

先看一個重要的文件Example.spec

spec文件是Pyinstaller打包成EXE的配置文件,是自動生成的,這裏我直接拿以前的進行修改,剛開始沒有的,可以直接隨便運行一次Pyinstaller來獲得,直接複製我的也可以。

# -*- mode: python -*-
 
block_cipher = None
 
 
a = Analysis(['Example.py'], # 主要打包的主py文件
       pathex=['C:\\Users\\abc\\Documents'], # 打包路徑
       binaries=None,
       datas=None,
       hiddenimports=[],
       hookspath=[],
       runtime_hooks=[],
       excludes=[],
       win_no_prefer_redirects=False,
       win_private_assemblies=False,
       cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
       cipher=block_cipher)
a.datas+= [('Exmaple.msi', r'C:\Users\abc\Documents\Example-1.0.win32.msi', 'DATA'),]# 附加文件,打包時加入到EXE文件中,讓我們可以在py文件中調用
exe = EXE(pyz,
     a.scripts,
     a.binaries,
     a.zipfiles,
     a.datas, # 打包文件列表
     name='examlpe',# exe文件的名字
     debug=False,
     strip=False,
     upx=True,
     console=True )

打開Example.spec所在的路徑,複製MSI安裝包到這裏,在dos窗口中運行

pyinstaller Example.spec

運行成功後,會生成build和dist兩個文件夾,我們依然只看dist文件夾,裏面example.exe就是我們所需要的

以上這篇Python封裝成可帶參數的EXE安裝包實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章