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

如何在Python脚本中判断Linux发行版(Ubuntu/CentOS)

判断Linux发行版的小技巧

嘿,这个需求很常见!你已经用platform.linux_distribution()拿到了包含发行版信息的元组,要提取第一个值(也就是发行版名称)其实超简单——直接用索引[0]就能搞定,之后就可以轻松做if判断啦。

先给你写个直观的代码示例:

import platform

# 先把发行版信息存下来,方便后续使用
distro_tuple = platform.linux_distribution()
# 提取元组里的第一个元素:发行版名称
distro_name = distro_tuple[0]

# 开始判断
if distro_name == 'Ubuntu':
    print("当前运行的是Ubuntu系统👍")
elif distro_name == 'CentOS':
    print("当前运行的是CentOS系统👍")
else:
    print(f"当前系统是{distro_name},不是你要找的Ubuntu或CentOS哦")

要是想更简洁点,也可以直接在判断里用索引,省去中间变量:

import platform

if platform.linux_distribution()[0] == 'Ubuntu':
    print("Ubuntu系统已识别")
elif platform.linux_distribution()[0] == 'CentOS':
    print("CentOS系统已识别")

友情提醒

不过得跟你说个重要信息:platform.linux_distribution()在Python 3.5及之后的版本已经被官方标记为废弃啦,未来可能会被移除。如果要更稳妥、兼容新Python版本的话,推荐用platform.freedesktop_os_release(),这个方法会返回一个字典,信息更全也更标准:

import platform

# 获取标准化的发行版信息字典
os_release_data = platform.freedesktop_os_release()
# 从字典里取出发行版名称
distro_name = os_release_data.get('NAME')

# 这里用in判断更灵活,比如有些发行版名称可能带后缀(比如"CentOS Linux")
if 'Ubuntu' in distro_name:
    print("识别到Ubuntu系统")
elif 'CentOS' in distro_name:
    print("识别到CentOS系统")

这个方法兼容性更强,建议优先考虑哦~

内容的提问来源于stack exchange,提问作者python maniac

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:29:08