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

来源:互联网 发布:怎么才能学好编程 编辑:程序博客网 时间:2024/06/08 12:24

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

  1. 将某几个源码文件夹进行打包,文件夹内有py文件、dll文件、exe文件等各种文件类型
  2. 打包生成的安装包,在进行安装的时候,应该能够带有参数,对配置文件进行修改配置
  3. 安装过程中,可以配置系统环境变量
  4. 能够检测环境,提示安装依赖包
  5. 整个过程要可以自动化,能够大量部署
综合考虑后,决定以下几个步骤完成:
  1. 用setup.py将源码文件夹都打包成msi安装包,这样可以使用msiexec进行静默安装
  2. setup.py可以提示用户安装依赖包,否则安装失败
  3. 再编写一个py文件,用来静默安装msi安装包,并配置系统环境变量,接受安装参数去修改配置文件的属性
  4. 最后使用pyinstaller将所有都打包成exe文件

先来编写setup.py文件:
# coding=utf-8from distutils.core import setupimport osdef get_all_dir(path):    """        获取指定路径下的所有文件    """    all_file = []    for dirpath, dirnames, filenames in os.walk(path):        for filename in filenames:            all_file.append(dirpath)    return all_fileif __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 subprocessconfig_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 winregENV_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### 设置系统环境变量所需代码 enddef 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:        passdef 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 = Nonea = 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就是我们所需要的




0 0
原创粉丝点击