• python 在window对exe、注册表、bat、系统服务操作等实例讲解


    目录

    前言:        

    1、python准备工作

    具体操作实例 

    实例1:调用exe文件

    实例2:调用bat批处理文件

    实例3:调用mis安装文件

    实例4: 操作注册表

    实例5: window系统服务的操作

     完整代码


    前言:        

        正在做的项目已经在中后期,需要一些工具链来节省开发,用python脚本实现自动化工具。以一个我写的python脚本为例,供大家参考。接着要讲的python包含如下内容:调用exe运行程序、调用mis安装文件、和批处理文件,创建、开启、关闭window服务、设置系统变量等。这里就以我做的几个为例,安装Java jdk、redis等作为实例来讲解,以供大家参考。

    1、python准备工作

            下载python版本,下载页面:Python Releases for Windows | Python.org,具体怎么安装,请在网上搜索即可,安装python不是本文需要讲的重点。

            选定一个编辑器,当然你可以也不选择,用普通文本编辑或其他编辑器都可以,但是我喜欢用编辑器编辑python代码。我选定的ide是 Pycharm社区版本。

    下载python社区版本

            Download PyCharm: Python IDE for Professional Developers by JetBrains

             

    具体操作实例 

    实例1:调用exe文件

    调用exe可执行文件,需要引用subprocess库文件

    import subprocess

    python函数执行代码如下:

    1. def runExe(path):
    2. try:
    3. process = subprocess.Popen([path])
    4. # 等待程序结束,并获取程序的返回值
    5. stdout, stderr = process.communicate()
    6. # 判断程序是否正常结束
    7. if process.returncode == 0:
    8. print(f'运行' + path + '成功')
    9. return process.returncode
    10. else:
    11. return process.returncode
    12. except Exception as e:
    13. print(f'安装'+ path+'异常:'+str(e))
    14. return -1

    在这里我们用到subprocess库运行exe文件;process.communicate()等待窗关闭,并执行接下来的代码

    实例2:调用bat批处理文件

    直接运行install_Redis.bat批处理文件

    1. # 安装redis
    2. def install_redis(curr_path):
    3. print('开始安装_redis')
    4. redis_path = curr_path + '\install\Redis-x64-5.0.14.1\install_Redis.bat'
    5. print('redis_path 路径' + redis_path)
    6. runBat('redis',redis_path)

    这里把调用bat文件直接封装成一个函数,同样需要用到subprocess库,不过等待返回结果是:process.check_returncode()

    1. # 运行批处理,name,定义批处理的名称,批处理curr_path实际的完整路径
    2. def runBat(name, curr_path):
    3. print(name + ' 路径' + curr_path)
    4. try:
    5. process = subprocess.run([curr_path])
    6. # 等待程序结束,并获取程序的返回值
    7. process.check_returncode()
    8. print(process.stdout)
    9. # 判断程序是否正常结束
    10. if process.returncode == 0:
    11. print(f'运行完' + name)
    12. else:
    13. print(f'程序执行失败,返回值为 {process.returncode}')
    14. except Exception as e:
    15. print(f'运行bat文件%s,发生异常 %s' % (curr_path, str(e)))

    实例3:调用mis安装文件

            调用mis文件与调用exe文件他们同样需要使用subprocess库,但是有些许的不同,主要表现在subprocess.Popen的参数上和返回值上,具体看如下代码:

    1. # 安装mongodb
    2. def install_mongodb(curr_path):
    3. print(f'开始安装_mongodb')
    4. mongdb_path = curr_path + r'\install\mongodb-win32-x86_64-2012plus-4.2.17-signed.msi'
    5. print(f'mongdb_path 路径' + mongdb_path)
    6. try:
    7. process = subprocess.Popen(['msiexec', '/i', mongdb_path])
    8. # 等待程序结束,并获取程序的返回值
    9. while True:
    10. if process.poll() is not None:
    11. print(mongdb_path + ' 文件执行完毕')
    12. break;
    13. except Exception as e:
    14. print(f'安装mongodb 失败 %s ' % str(e))

    这里subprocess.Popen用到参数数组['msiexec', '/i', mongdb_path] 

    实例4: 操作注册表

    操作注册表我们需要引用的库为winreg

    import winreg

    实例代码如下:

    1. # 设置注册表信息
    2. def setWinregKey(regKey, path):
    3. print(f'创建 {regKey} 环境变量')
    4. # 打开注册表
    5. key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment', 0, winreg.KEY_ALL_ACCESS)
    6. # 添加环境变量
    7. winreg.SetValueEx(key, regKey, 0, winreg.REG_SZ, path)
    8. winreg.FlushKey(key)
    9. winreg.CloseKey(key)

    实例5: window系统服务的操作

    对于window服务,同样我们需要用到subprocess库,以我自己注册zookeeper服务为例

    1. # 安装 zookeeper,并启动zookeeper服务
    2. def install_zookeeper(curr_path):
    3. print(f'创建zookeeper环境变量')
    4. setWinregKey('ZOOKEEPER_HOME', curr_path + r'\install\zookeeper\apache-zookeeper-3.7.0-bin')
    5. setWinregKey('ZOOKEEPER_SERVICE', 'zookeeper_service')
    6. try:
    7. if service_exists('zookeeper_service'):
    8. cmdRun(['net', 'stop', 'zookeeper_service'])
    9. cmdRun(['sc', 'delete', 'zookeeper_service'])
    10. runBat('zookeeper', curr_path + r'\install\zookeeper' + r'\apache-zookeeper-3.7.0-bin\bin\Install.bat')
    11. cmdRun(['net', "start", 'zookeeper_service'])
    12. except Exception as e:
    13. print(u'%s' % (str(e)))

    该函数功能是:判断zookeeper服务是否存在,如果存在,关闭并删除,并启动bat文件注册zookeeper服务,并启动zookeeper服务 

     自己定义的函数:

    运行cmd单条命令函数processRun:

    1. # 执行cmd命令,如:开启服务 window服务net start zookeeper_service
    2. def cmdRun(args):
    3. try:
    4. ret = subprocess.run(args, check=True)
    5. # ret.returncode 返回int类型,0 则执行成功
    6. ret.check_returncode()
    7. print('ret.returncode: %d' % ret.returncode)
    8. print('ret.stdout: %s' % ret.stdout)
    9. except Exception as e:
    10. print(f'运行命令 %s 发生异常' % (str(e)))

    判断服务是否存在函数:

            通过sc query [service_name]命令查询服务器是否存在

    1. # 判断服务是否存在
    2. def service_exists(service_name):
    3. try:
    4. subprocess.check_output(['sc', 'query', service_name])
    5. return True
    6. except subprocess.CalledProcessError:
    7. return False

     完整代码

            最后这里给出完整代码供大家作个简单的参考,可能有些遗漏或有瑕疵的地方,这里主要是抛砖引玉。

    1. # -*- coding: utf-8 -*-
    2. # This is a sample Python script.
    3. # Press Shift+F10 to execute it or replace it with your code.
    4. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
    5. # encoding=utf-8
    6. import os
    7. import subprocess
    8. import winreg
    9. # See PyCharm help at https://www.jetbrains.com/help/pycharm/
    10. # 获得当前路径
    11. def getCurrentDir():
    12. file_path = os.path.abspath(__file__)
    13. dir_path = os.path.dirname(file_path)
    14. return dir_path
    15. def installServer(name):
    16. # Use a breakpoint in the code line below to debug your script.
    17. print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
    18. curr_path = getCurrentDir()
    19. print(getCurrentDir())
    20. # install_java_sdk(curr_path)
    21. # install_redis(curr_path)
    22. # install_mongodb(curr_path)
    23. install_zookeeper(curr_path)
    24. # install_idea(curr_path)
    25. def install_java_sdk(curr_path):
    26. print(f'开始安装java sdk')
    27. jdk = curr_path + r'\install\jdk-11.0.11_windows-x64_bin.exe'
    28. print(f'jdk 路径' + jdk)
    29. try:
    30. returnCode = runExe(jdk)
    31. # 判断程序是否正常结束
    32. if returnCode == 0:
    33. print(f'创建java sdk环境变量')
    34. # 打开注册表
    35. key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment', 0, winreg.KEY_ALL_ACCESS)
    36. # 添加环境变量
    37. winreg.SetValueEx(key, 'JAVA_HOME', 0, winreg.REG_SZ, 'C:\Program Files\Java\jdk-11.0.11')
    38. # 关闭注册表
    39. winreg.CloseKey(key)
    40. else:
    41. print(f'程序执行失败,返回值为')
    42. except Exception as e:
    43. print('安装java sdk 异常 %s 结束安装' % str(e))
    44. # 安装mongodb
    45. def install_mongodb(curr_path):
    46. print(f'开始安装_mongodb')
    47. mongdb_path = curr_path + r'\install\mongodb-win32-x86_64-2012plus-4.2.17-signed.msi'
    48. print(f'mongdb_path 路径' + mongdb_path)
    49. try:
    50. process = subprocess.Popen(['msiexec', '/i', mongdb_path])
    51. # 等待程序结束,并获取程序的返回值
    52. while True:
    53. if process.poll() is not None:
    54. print(mongdb_path + ' 文件执行完毕')
    55. break;
    56. except Exception as e:
    57. print(f'安装mongodb 失败 %s ' % str(e))
    58. # 安装redis
    59. def install_redis(curr_path):
    60. print('开始安装_redis')
    61. redis_path = curr_path + '\install\Redis-x64-5.0.14.1\install_Redis.bat'
    62. print('redis_path 路径' + redis_path)
    63. runBat('redis',redis_path)
    64. # 判断服务是否存在
    65. def service_exists(service_name):
    66. try:
    67. subprocess.check_output(['sc', 'query', service_name])
    68. return True
    69. except subprocess.CalledProcessError:
    70. return False
    71. # 安装 zookeeper,并启动zookeeper服务
    72. def install_zookeeper(curr_path):
    73. print(f'创建zookeeper环境变量')
    74. setWinregKey('ZOOKEEPER_HOME', curr_path + r'\install\zookeeper\apache-zookeeper-3.7.0-bin')
    75. setWinregKey('ZOOKEEPER_SERVICE', 'zookeeper_service')
    76. try:
    77. if service_exists('zookeeper_service'):
    78. cmdRun(['net', 'stop', 'zookeeper_service'])
    79. cmdRun(['sc', 'delete', 'zookeeper_service'])
    80. runBat('zookeeper', curr_path + r'\install\zookeeper' + r'\apache-zookeeper-3.7.0-bin\bin\Install.bat')
    81. cmdRun(['net', "start", 'zookeeper_service'])
    82. except Exception as e:
    83. print(u'%s' % (str(e)))
    84. def install_idea(curr_path):
    85. print(f'开始安装 idea')
    86. idea = curr_path + r'\install\ideaIU-2019.3.4\ideaIU-2019.3.4.exe'
    87. print(f'idea 路径' + idea)
    88. runExe(idea)
    89. # 执行cmd命令,如:开启服务 window服务net start zookeeper_service
    90. def cmdRun(args):
    91. try:
    92. ret = subprocess.run(args, check=True)
    93. # ret.returncode 返回int类型,0 则执行成功
    94. ret.check_returncode()
    95. print('ret.returncode: %d' % ret.returncode)
    96. print('ret.stdout: %s' % ret.stdout)
    97. except Exception as e:
    98. print(f'运行命令 %s 发生异常' % (str(e)))
    99. def runExe(path):
    100. try:
    101. process = subprocess.Popen([path])
    102. # 等待程序结束,并获取程序的返回值
    103. stdout, stderr = process.communicate()
    104. # 判断程序是否正常结束
    105. if process.returncode == 0:
    106. print(f'运行' + path + '成功')
    107. return process.returncode
    108. else:
    109. return process.returncode
    110. except Exception as e:
    111. print(f'安装'+ path+'异常:'+str(e))
    112. return -1
    113. # 设置注册表信息
    114. def setWinregKey(regKey, path):
    115. print(f'创建 {regKey} 环境变量')
    116. # 打开注册表
    117. key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment', 0, winreg.KEY_ALL_ACCESS)
    118. # 添加环境变量
    119. winreg.SetValueEx(key, regKey, 0, winreg.REG_SZ, path)
    120. winreg.FlushKey(key)
    121. winreg.CloseKey(key)
    122. # 运行批处理,name,定义批处理的名称,批处理curr_path实际的完整路径
    123. def runBat(name, curr_path):
    124. print(name + ' 路径' + curr_path)
    125. try:
    126. process = subprocess.run([curr_path])
    127. # 等待程序结束,并获取程序的返回值
    128. process.check_returncode()
    129. print(process.stdout)
    130. # 判断程序是否正常结束
    131. if process.returncode == 0:
    132. print(f'运行完' + name)
    133. else:
    134. print(f'程序执行失败,返回值为 {process.returncode}')
    135. except Exception as e:
    136. print(f'运行bat文件%s,发生异常 %s' % (curr_path, str(e)))
    137. # Press the green button in the gutter to run the script.
    138. if __name__ == '__main__':
    139. installServer('install')

            

  • 相关阅读:
    LeetCode每日一题(1540. Can Convert String in K Moves)
    【Java 进阶篇】JDBC Statement:执行 SQL 语句的重要接口
    EasyExcel的使用(包含动态表头)
    创建一个GO模块
    [Linux]线程同步
    jQuery 的实现原理
    【Gradle】四、使用Gradle创建SringBoot微服务项目
    信息化与信息系统4
    Beacon帧
    免费分享一个springboot+vue学生选课管理系统,挺漂亮的
  • 原文地址:https://blog.csdn.net/lejian/article/details/132909081