Search code examples
pythonpython-2.7centosrhelcentos7

How to reliably check if I am above a certain CentOS version (CentOS 7) in a Python script?


I have been given a task to port a bunch of our internal applications from CentOS6 to CentOS7. With this move, we are changing our dependencies from external packages that we have repackaged ourselves to official upstream version of the packages.

Because of this I am looking for a reliable piece of python2.7 code that will do this:

if CentOS version >= 7:
    do things the new way
else:
    do things the deprecated way

It will be used for autogenerating .spec files to make RPMs.

I've been looking at things like parsing /etc/redhat-release but that seems a little bit unreliable for what I want. Is there a better way?

Thanks very much.


Solution

  • You could also try:

    In [1]: import platform
    
    In [2]: platform.linux_distribution()
    Out[2]: ('Red Hat Enterprise Linux Server', '6.5', 'Santiago')
    
    In [3]: dist = platform.linux_distribution()
    
    In [4]: "Red Hat" in dist[0] and dist[1].split('.')[0] == '6'
    Out[4]: True
    
    In [5]:
    

    hth