侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python封装成可带参数的EXE安装包实例

Python  /  管理员 发布于 7年前   293

最近有一个小项目,有如下的需求:

将某几个源码文件夹进行打包,文件夹内有py文件、dll文件、exe文件等各种文件类型

打包生成的安装包,在进行安装的时候,应该能够带有参数,对配置文件进行修改配置

安装过程中,可以配置系统环境变量

能够检测环境,提示安装依赖包

整个过程要可以自动化,能够大量部署

综合考虑后,决定以下几个步骤完成:

用setup.py将源码文件夹都打包成msi安装包,这样可以使用msiexec进行静默安装

setup.py可以提示用户安装依赖包,否则安装失败

再编写一个py文件,用来静默安装msi安装包,并配置系统环境变量,接受安装参数去修改配置文件的属性

最后使用pyinstaller将所有都打包成exe文件

先来编写setup.py文件:

# coding=utf-8from distutils.core import setupimport 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-8import osimport sysimport subprocess config_file = r"C:\Python27\Lib\site-packages\B\lib\configuration\config.cfg" import sysfrom subprocess import check_call  ### 设置系统环境变量所需代码if sys.hexversion > 0x03000000:  import winregelse:  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安装包实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


  • 上一条:
    python+selenium select下拉选择框定位处理方法
    下一条:
    python识别文字(基于tesseract)代码实例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客