判断Python是否在Ubuntu Linux中运行

13 投票
6 回答
5620 浏览
提问于 2025-04-17 07:27

我有一个用Python 3.2写的程序,它的运行方式是这样的:

import platform
sysname = platform.system()
sysver = platform.release()
print(sysname+" "+sysver)

在Windows系统上,它返回的是:

Windows 7

但是在Ubuntu和其他系统上,它返回的是:
Linux 3.0.0-13-generic

我需要的结果是像这样的:

Ubuntu 11.10 或者 Mint 12

6 个回答

6

目前被接受的答案使用了一个已经不再推荐使用的函数。从Python 2.6及以后版本,正确的做法是:

import platform
print(platform.linux_distribution())

文档没有说明这个函数在非Linux平台上是否可用,但在我的Windows桌面上,我得到了:

>>> import platform
>>> print(platform.linux_distribution())
('', '', '')

还有这个方法,可以在Win32机器上做类似的事情:

>>> print(platform.win32_ver())
('post2008Server', '6.1.7601', 'SP1', 'Multiprocessor Free')
8

看起来 platform.dist()platform.linux_distribution() 在 Python 3.5 中已经被标记为不推荐使用,并且会在 Python 3.8 中被移除。

下面的代码在 Python 2 和 3 中都可以正常工作。

import platform
'ubuntu' in platform.version().lower()

示例返回值

>>> platform.version()
'#45~20.04.1-Ubuntu SMP Mon Apr 4 09:38:31 UTC 2022'
5

试试 platform.dist 这个方法。

>>> platform.dist()
('Ubuntu', '11.10', 'oneiric')

撰写回答