Python 2 subprocess (dmidecode) to a variable?

1k views Asked by At

I'm running a dmidecode in linux to get the list of hardware information. What is the best way to read over the output and select certain bits of information? For example get the Product Name: part of the dmidecode?

At the moment I'm writing the subprocess output to a file then reading over the file for a given string. This seems such an inefficient way of doing things.

Also I know about the python dmidecode model but for the life of me I can't get it working it just keeps saying there's no bios attribute

2

There are 2 answers

3
Mathieu Coavoux On

If you know the specific keyword you are looking for you can type: dmidecode -s keyword

In your case it would be:

dmidecode -s system-product-name

You can also filter by type. For example:

  • To return System information:

    dmidecode -t1
    
  • To return BaseBoard information:

    dmidecode -t2 
    
  • To return Chassis Information:

    dmidecode -t3
    
5
Anand S Kumar On

There are multiple ways with which you can get the output of the command in your python script using subprocess module.

  1. subprocess.Popen() - you can start the command line process using this Popen class specifying stdout as subprocess.PIPE and then use communicate function to get the results. Example -

    import subprocess
    p = subprocess.Popen(['dmidecode'] , stdout=subprocess.PIPE)
    result = p.communicate()[0]
    
  2. subprocess.check_output() - this function returns the output of the command (output to stdout) as a byte string after executing the command. Example -

    import subprocess
    result = subprocess.check_output(['dmidecode'])
    

For your particular case, subprocess.check_output() is most probably more suited as you do not need to provide any inputs to the process.

With subprocess.Popen() you can also need to provide inputs to the process , by PIPING the stdin for the process.