Determine if python is being run in Ubuntu Linux

Question:

I have a Python 3.2 program that runs like this:

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

And on windows it returns:

Windows 7

But on Ubuntu and others it returns:
Linux 3.0.0-13-generic

I need something like:

Ubuntu 11.10 or Mint 12

Asked By: triunenature

||

Answers:

Try platform.dist.

>>> platform.dist()
('Ubuntu', '11.10', 'oneiric')
Answered By: Matt Joiner

Or, you could do this:

import sys
sys.platform

It would return: ‘linux2’, or you could implement try..finally code block.

Answered By: jermenkoo

The currently accepted answer uses a deprecated function. The proper way to do this as of Python 2.6 and later is:

import platform
print(platform.linux_distribution())

The documentation doesn’t say if this function is available on non-Linux platforms, but on my local Windows desktop I get:

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

There’s also this, to do something similar on Win32 machines:

>>> print(platform.win32_ver())
('post2008Server', '6.1.7601', 'SP1', 'Multiprocessor Free')
Answered By: unwind
is_ubuntu = 'ubuntu' in os.getenv('DESKTOP_SESSION', 'unknown')

Picks up if you are runnning in Unity or Unity-2D if that is what you are looking for.

Answered By: bulletmark

Looks like platform.dist() and platform.linux_distribution() are deprecated in Python 3.5 and will be removed in Python 3.8. The following works in Python 2/3

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

Example return value

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

Many of the solutions do not work when executing inside a Container (The result is the host distro instead.)

Less elegant – but container friendly approach:

from typing import Dict

def parse_env_file(path: str) -> Dict[str, str]:
    with open(path, 'r') as f:                                               
        return dict(tuple(line.replace('n', '').split('=')) for line in f.readlines() if not line.startswith('#'))

def is_ubuntu() -> bool:
    return "ubuntu" in parse_env_file("/etc/os-release")["NAME"].lower())
Answered By: Daniel Braun
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.