Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to determine the specific Linux distribution being used?

Tags:

python

linux

I would like to know how to determine the precise Linux distribution I am on (excluding version numbers), from within a Python script and define a variable as equal to it. Now, I should clarify and say that I have seen these two questions:

  • Python: What OS am I running on?
  • How can I find the current OS in Python?

and neither one was helpful to me as, the first of these questions had answers that were very generalized and merely returned posix for all Linux distributions. The second question's answers weren't helpful as I sometimes operate on some more obscure distributions like Manjaro Linux and Sabayon Linux. The most applicable answer to the second question, was platform.linux_distribution(), which on Manjaro, returns:

('', '', '')

which as you can see is not helpful. Now I know a way I can get half-way to an acceptable answer, as:

from subprocess import call
call(["lsb_release", "-si"])

returns the output (on Manjaro Linux, of course):

ManjaroLinux
0

but defining a variable:

a=call(["lsb_release", "-si"])

gives an a with the value:

>>> a
0
like image 203
Josh Pinto Avatar asked Feb 09 '23 01:02

Josh Pinto


2 Answers

The 'a' is just the exit status, try:

from subprocess import Popen, PIPE, STDOUT
cmd = "lsb_release -si"
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = p.stdout.read()
like image 155
Mike Vella Avatar answered Feb 10 '23 14:02

Mike Vella


Replace call with check_output.

from subprocess import check_output
a = check_output(["lsb_release", "-si"])
like image 45
dyeray Avatar answered Feb 10 '23 14:02

dyeray