如何用Python脚本检查Python是否已安装?Windows PyInstaller部署场景
Python安装脚本:检查Python是否已安装的实现方案
需求与现有代码
需要编写可通过PyInstaller转为Windows可执行文件的脚本,核心功能为:检查系统是否已安装Python,未安装则自动下载对应架构的Python安装包并执行安装。现有代码已实现下载与安装逻辑,但缺少Python存在性检查部分:
import subprocess, requests, platform architecture = platform.uname()[4] if architecture == 'AMD64': executable_file = "https://www.python.org/ftp/python/3.11.1/python-3.11.1-amd64.exe" elif architecture == 'ARM64': executable_file = "https://www.python.org/ftp/python/3.11.1/python-3.11.1-arm64.exe" r = requests.get(executable_file) with open("python-3.11.1-amd64.exe",'wb') as f: f.write(r.content) cmd = "python-3.11.1-amd64.exe" returned_value = subprocess.call(cmd, shell=True) if returned_value == 1602: print("Installation Cancelled. Exitting.") quit() print('returned value:', returned_value)
检查Python是否已安装的实现思路
方法1:尝试调用Python命令
Windows下可通过python或py(Python官方启动器)命令检测:
- 使用
subprocess.run调用python --version或py --version,设置check=True捕获异常,若抛出CalledProcessError或FileNotFoundError,则判定Python未安装。
方法2:读取Windows注册表
Python安装时会将路径信息写入注册表,可通过winreg模块读取以下路径验证:
- 系统级安装:
HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\<版本号>\InstallPath - 用户级安装:
HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\<版本号>\InstallPath
若能读取到有效路径,则说明对应版本Python已安装。
方法3:检查常见安装路径
遍历Windows下Python的常规安装目录,判断是否存在python.exe:
- 系统默认路径:
C:\Python311(对应3.11版本) - 用户自定义路径:
C:\Users\<用户名>\AppData\Local\Programs\Python\Python311
整合检查逻辑后的完整代码
以下是整合了**方法1(命令检测)**的完整脚本,同时修复了原代码中文件名与架构不匹配的问题:
import subprocess import requests import platform import sys def is_python_installed(): # 尝试调用python命令 try: subprocess.run(["python", "--version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return True except (subprocess.CalledProcessError, FileNotFoundError): # 尝试调用py启动器命令 try: subprocess.run(["py", "--version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return True except (subprocess.CalledProcessError, FileNotFoundError): return False if __name__ == "__main__": if is_python_installed(): print("Python已安装,无需执行安装流程。") sys.exit(0) # 下载对应架构的Python安装包 architecture = platform.uname()[4] if architecture == 'AMD64': exe_name = "python-3.11.1-amd64.exe" executable_file = f"https://www.python.org/ftp/python/3.11.1/{exe_name}" elif architecture == 'ARM64': exe_name = "python-3.11.1-arm64.exe" executable_file = f"https://www.python.org/ftp/python/3.11.1/{exe_name}" else: print(f"不支持的系统架构:{architecture}") sys.exit(1) print(f"开始下载Python安装包:{executable_file}") r = requests.get(executable_file) with open(exe_name, 'wb') as f: f.write(r.content) # 执行安装 print("开始执行Python安装...") returned_value = subprocess.call(exe_name, shell=True) if returned_value == 1602: print("安装已取消,退出程序。") sys.exit(1) elif returned_value == 0: print("Python安装成功!") else: print(f"安装过程返回异常值:{returned_value}")
内容的提问来源于stack exchange,提问作者Ruler
相关产品推荐
相关产品推荐

