-1

I chose this way to get linux distro name:

ls /etc/*release

And now I have to parse it for name:

/etc/<name>-release

def checkDistro():
    p = Popen('ls /etc/*release' , shell = True, stdout = PIPE)
    distroRelease = p.stdout.read()

    distroName = re.search( ur"\/etc\/(.*)\-release", distroRelease).group()
    print distroName

But this prints the same string that is in distroRelease.

2
  • 4
    You might want to use the Linux Standard Base tool "lsb_release" instead. Run it with --help and/or -a to get a feel of how it works. May 3, 2010 at 8:36
  • 1
    As you may already know, /etc/*release won't work for all distros. But see serverfault.com/questions/3331/…
    – Jonik
    May 3, 2010 at 8:37

5 Answers 5

7

An alternative is to use the builtin method platform.linux_distribution() (available in Python 2.6+):

>>> import platform
>>> platform.linux_distribution()
('Red Hat Enterprise Linux Server', '5.1', 'Tikanga')

In older versions of Python, platform.dist() can be used:

>>> import platform
>>> platform.dist()
('redhat', '5.1', 'Tikanga')
5

You need .group(1), because you want the first capture group - without arguments, it defaults to .group(0) which is the entire matched text.

3

Parsing ls output is discouraged. Consider using a glob():

#!/usr/bin/env python

import os
import glob

def check_distro():
    print os.path.basename(glob.glob('/etc/*-release')[0]).replace('-release', '')

if __name__ == '__main__':
    check_distro()
2

Use .group(1).

1

What's the point? /etc/*release is not a standard, it will only work on some distros.

3
  • 1
    I know that. This script will work only under distros which supports this file.
    – Max Frai
    May 3, 2010 at 8:42
  • 4
    @Lo'oris: that's not really up to you to judge, is it? If OP chooses to create the script this way despite the limitation, then it very likely will be useful to him.
    – Jonik
    May 3, 2010 at 10:20
  • Since there is a better way to do that, as pointed out by Magnus Hoff in his comment, this way is just wrong and should be avoided.
    – o0'.
    May 3, 2010 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.