views:

76

answers:

5

Hello, 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.

+5  A: 

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

Amber
+2  A: 

Use .group(1).

Marcelo Cantos
+1  A: 

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

Lo'oris
I know that. This script will work only under distros which supports this file.
Ockonal
Then it will be useless.
Lo'oris
@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
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.
Lo'oris
+3  A: 

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()
Latchezar Tzvetkoff
+5  A: 

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')
David Narayan