You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python获取Windows版本?含模拟CMD程序功能实现需求

如何用Python查看Windows版本&在模拟CMD程序中实现该功能

Hey there! Let's break down your two questions step by step—first, how to get Windows version info in Python generally, then how to build that into your CMD simulator project.

一、通用Python查看Windows版本的方法

这里有几种靠谱的方式,从简单到底层都有,你可以根据需求选:

1. 使用platform模块(最省心的标准库方案)

Python自带的platform模块专门用来获取系统信息,不用额外装包,代码超简洁:

import platform

# 获取完整系统快照
system_details = platform.uname()
print(f"Windows版本描述: {system_details.version}")
print(f"版本号(如10/11): {system_details.release}")

# 专门针对Windows的详细信息
win_specific = platform.win32_ver()
print(f"版本名称(如Windows 10 Pro): {win_specific[0]}")
print(f"版本号: {win_specific[1]}")
print(f"服务包信息: {win_specific[2]}")

这个方法适合快速获取信息,缺点是有时候返回的版本名称不够细致(比如可能只显示"Windows 10"而不是"Windows 10 Pro")。

2. 读取Windows注册表(获取最友好的版本名称)

Windows把版本的详细信息存在注册表中,我们可以用winreg模块读取,能拿到像"Windows 11 Pro"这种用户熟悉的名称:

import winreg

def get_win_version_from_reg():
    try:
        # 打开注册表路径
        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion") as reg_key:
            product_name = winreg.QueryValueEx(reg_key, "ProductName")[0]
            build_number = winreg.QueryValueEx(reg_key, "CurrentBuild")[0]
            release_id = winreg.QueryValueEx(reg_key, "ReleaseId")[0]
            return f"{product_name} (Build {build_number}, Release ID: {release_id})"
    except Exception as e:
        return f"读取失败: {str(e)}"

# 调用函数
print(get_win_version_from_reg())

这个方法的输出更贴近用户平时看到的Windows版本信息,适合需要展示友好名称的场景。

3. 调用Windows API(底层精准获取)

如果需要最底层、最准确的版本参数(比如主版本号、次版本号、构建号),可以用ctypes直接调用Windows的API:

import ctypes
from ctypes import wintypes

# 定义API需要的结构体
class OSVERSIONINFOEXW(ctypes.Structure):
    _fields_ = [
        ('dwOSVersionInfoSize', wintypes.DWORD),
        ('dwMajorVersion', wintypes.DWORD),
        ('dwMinorVersion', wintypes.DWORD),
        ('dwBuildNumber', wintypes.DWORD),
        ('dwPlatformId', wintypes.DWORD),
        ('szCSDVersion', wintypes.WCHAR * 128),
        ('wServicePackMajor', wintypes.WORD),
        ('wServicePackMinor', wintypes.WORD),
        ('wSuiteMask', wintypes.WORD),
        ('wProductType', wintypes.BYTE),
        ('wReserved', wintypes.BYTE)
    ]

# 初始化结构体并调用API
os_info = OSVERSIONINFOEXW()
os_info.dwOSVersionInfoSize = ctypes.sizeof(os_info)
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

if not kernel32.GetVersionExW(ctypes.byref(os_info)):
    raise ctypes.WinError(ctypes.get_last_error())

# 打印底层信息
print(f"主版本号: {os_info.dwMajorVersion}")
print(f"次版本号: {os_info.dwMinorVersion}")
print(f"构建号: {os_info.dwBuildNumber}")
print(f"服务包版本: {os_info.wServicePackMajor}.{os_info.wServicePackMinor}")

注意:Windows 10及以上系统,如果你的Python程序没有应用清单文件,这个API可能返回不正确的版本号(比如把Win11识别成Win10)。如果需要解决这个问题,可以给程序添加应用清单,或者改用读取kernel32.dll文件版本的方式。

二、在模拟CMD程序中实现ver命令功能

要让你的CMD模拟器的ver命令和原生CMD的输出风格一致,我们可以结合上面的方法,用Python的cmd模块搭建基础框架,再集成版本查询功能。

完整示例代码

import cmd
import winreg
import platform

class CmdSimulator(cmd.Cmd):
    # 模拟CMD的提示符
    prompt = 'C:\\>'

    def do_ver(self, arg):
        """显示Windows版本信息(和原生CMD的ver命令输出一致)"""
        try:
            # 优先从注册表获取友好名称和详细构建信息
            with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion") as reg_key:
                product_name = winreg.QueryValueEx(reg_key, "ProductName")[0]
                current_build = winreg.QueryValueEx(reg_key, "CurrentBuild")[0]
                ubr = winreg.QueryValueEx(reg_key, "UBR")[0]  # 更新构建版本号
            
            # 完全模仿原生CMD的输出格式
            print(f"Microsoft Windows [{product_name}]")
            print(f"版本 {platform.release()}.{current_build}.{ubr}")
        except Exception as e:
            # 注册表读取失败时,用platform模块作为备选方案
            print(f"Microsoft Windows [{platform.system()} {platform.release()}]")
            print(f"版本 {platform.version()}")

    def do_exit(self, arg):
        """退出模拟CMD程序"""
        print("正在退出...")
        return True

if __name__ == '__main__':
    # 启动模拟器
    simulator = CmdSimulator()
    simulator.cmdloop("欢迎使用模拟CMD!输入'ver'查看Windows版本,输入'exit'退出程序")

可选方案:直接调用原生ver命令

如果你想完全复刻原生CMD的ver输出(连格式都分毫不差),可以用subprocess调用系统的ver命令并捕获输出:

import subprocess

def get_native_ver_output():
    result = subprocess.run(['ver'], capture_output=True, text=True, shell=True)
    if result.returncode == 0:
        print(result.stdout)
    else:
        print("无法获取版本信息")

# 在你的CMD模拟器中,把do_ver方法替换成调用这个函数即可

这个方案的优点是输出完全和原生一致,缺点是依赖系统的CMD环境,在某些受限场景下可能无法使用。


内容的提问来源于stack exchange,提问作者Luka Mamukashvili

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:44:49