Determine if python is running on Ubuntu Linux

I have a Python 3.2 program that works as follows:

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

And in the 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

+10
python linux ubuntu
source share
5 answers

Try platform.dist .

 >>> platform.dist() ('Ubuntu', '11.10', 'oneiric') 
+6
source share

The currently accepted answer uses an obsolete function. The correct way to do this with Python 2.6 and later:

 import platform print(platform.linux_distribution()) 

The documentation does not indicate whether this feature is available on platforms other than Linux, 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') 
+5
source share

Updated to refer to the fact that this feature is planned to be removed in 3.8

It 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.platform().lower() 

Return Value Example

 >>> platform.platform() 'Linux-4.10.0-40-generic-x86_64-with-Ubuntu-16.04-xenial' 
+2
source share

Or you could do this:

 import sys sys.platform 

It will return: "linux2", or you can implement a try..finally code block.

0
source share
 is_ubuntu = 'ubuntu' in os.getenv('DESKTOP_SESSION', 'unknown') 

Selects if you are running Unity or Unity-2D, if that is what you are looking for.

-one
source share

All Articles