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

如何通过Python脚本获取Python版本的build编号?

How to Get Python's RPM Build Number via Python Script

Nice question! The standard sys and platform modules are great for grabbing Python's core version info, but they don't expose RPM-specific build metadata like the 48 in python-2.7.5-48.el7.x86_64. Fortunately, you can absolutely retrieve this from within Python by executing the RPM command and parsing its output. Here's a reliable approach:

The Approach

We'll use Python's subprocess module to run an RPM query (with a custom output format to make parsing easier), then extract the build number from the result. This avoids messy string matching on raw rpm -qa output and targets exactly the data we need.

Example Code

import subprocess

def fetch_python_rpm_build_number():
    try:
        # Run RPM query with structured output to get name, version, and release
        rpm_output = subprocess.run(
            ["rpm", "-qa", "--queryformat", "%{NAME}-%{VERSION}-%{RELEASE}\n"],
            capture_output=True,
            text=True,
            check=True
        )
        
        # Iterate through output lines to find Python packages
        for line in rpm_output.stdout.splitlines():
            # Match main Python packages (adjust if you need specific variants like python-devel)
            if line.startswith("python") or line.startswith("python3"):
                # Split the line into components: e.g., "python-2.7.5-48.el7" → ["python", "2.7.5", "48.el7"]
                package_parts = line.split("-")
                # The release segment contains the build number + distro tag
                release_segment = package_parts[-1]
                # Extract the build number (before the distro dot, e.g., "48" from "48.el7")
                build_number = release_segment.split(".")[0]
                return build_number
        
        # No matching Python package found
        return None
    except subprocess.CalledProcessError:
        # Command failed (likely not an RPM-based system)
        return None
    except IndexError:
        # Parsing failed due to unexpected output format
        return None

# Test the function
build_num = fetch_python_rpm_build_number()
if build_num:
    print(f"Python RPM build number: {build_num}")
else:
    print("Could not retrieve the RPM build number—this may not be an RPM-based system, or the Python package wasn't found.")

Key Notes

  • RPM-Specific: This only works on RPM-based systems like RHEL, CentOS, Fedora, etc. It won't work on Debian/Ubuntu (which use dpkg) or non-Linux systems.
  • Precision: Using --queryformat gives us structured output, which is more reliable than piping to grep directly—we avoid matching unrelated packages that include "python" in their name.
  • Permissions: Most users can run rpm -qa without root access, so this should work in most environments.

If you need to target a specific Python package (like python-devel instead of the main runtime), just adjust the string check in the loop to match your desired package name.

内容的提问来源于stack exchange,提问作者Vatsal Prakash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:33:39