Python3中platform.dist与platform.linux_distribution的替代方案及发行版名称获取咨询
嘿,这个问题我之前升级Python版本的时候也碰到过,确实挺闹心的——毕竟那俩方法用习惯了突然被弃用,一时找不到替代。不过别担心,有几个靠谱的方案,我给你梳理下:
替代platform.dist()和platform.linux_distribution()的可行方案
1. 官方推荐的platform模块新方法(Python 3.7+)
如果你之后计划升级到Python 3.7及以上版本,官方专门提供了替代方法platform.freedesktop_os_release(),它会返回一个包含发行版详细信息的字典,用起来很直观:
import platform os_details = platform.freedesktop_os_release() print(f"发行版名称: {os_details['NAME']}") print(f"版本号: {os_details['VERSION_ID']}")
这个方法完全遵循freedesktop规范,是官方认可的长期替代方案。
2. 直接读取系统文件(兼容Python 3.6及更早版本)
现代Linux发行版基本都遵循freedesktop规范,会把发行版信息存在/etc/os-release文件里。我们可以直接读取并解析这个文件,兼容性拉满:
def get_linux_distro(): distro_info = {} try: with open('/etc/os-release', 'r') as f: for line in f: line = line.strip() if not line or line.startswith('#'): continue key, val = line.split('=', 1) # 去掉值两端的引号 distro_info[key] = val.strip('"') return distro_info.get('NAME'), distro_info.get('VERSION_ID') except FileNotFoundError: # 针对极少数没有/etc/os-release的老系统,暂时fallback到弃用方法(3.6还能用) import platform return platform.linux_distribution()[:2] dist_name, dist_version = get_linux_distro() print(f"当前发行版: {dist_name} {dist_version}")
这个方法不管你用的是Python 3.6还是更高版本,只要是主流Linux发行版都能正常工作,而且完全不依赖即将被移除的API。
3. 第三方库简化操作
如果你不想自己写解析逻辑,可以用专门的第三方库distro,它专门处理Linux发行版信息的获取,兼容各种Python版本,而且封装得很友好:
先安装库:
pip install distro
然后使用:
import distro print(f"发行版: {distro.name()}") print(f"版本: {distro.version()}") print(f"完整信息: {distro.info()}")
这个库内部也是基于系统标准文件做解析,维护得很活跃,适合长期使用。
最后提醒下:虽然你当前用的Python 3.6还能使用platform.linux_distribution(),但尽量尽快迁移到上面的方案,避免之后升级到3.7+出现代码报错。
内容的提问来源于stack exchange,提问作者O_o
相关产品推荐
相关产品推荐

