-3

my command prints following output:

   -------------------------------------------------------------------------
   Producing details for server state
   ------------------------------------------------------------------------

  power:ok
  fault:none
  state:assigned
  load:normal 

I read the python Dictionary documentation:

myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
myCat['size']
output: fat

Like python Dictionary. How do I print power state, load

so what I want to here is, i have to redirect output file to like this:

Note: the command line output lines are random (length of file output is not constant)

serverstate = {'powerstate': 'ok', 'load': 'normal'}

so that I will print serverstate['powerstate']. I will get the value.

Please advise. If i am in wrong track.

meteor23
  • 267
  • 3
  • 6
  • 11

1 Answers1

1

When you say "my command prints following output", I assume you mean that you have an executable or something similar, which is unrelated to your Python script, which prints that output when you run it. Let's call it check_server_state.exe.

You can use subprocess.check_output to get the output of an executable into a string. Then you can iterate through the lines of that string and extract the key-value pairs.

import subprocess
s = subprocess.check_output("check_server_state.exe") #or whatever the actual name is
d = {}
for line in s.split("\n"):
    if ":" not in line:
        continue
    key, value = line.strip().split(":", 1)
    d[key] = value

print(d)
print(d["power"])

Result:

{'load': 'normal', 'fault': 'none', 'state': 'assigned', 'power': 'ok'}
ok
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • Hi Kevin, Thanks a lot. it is working. but could you please explain what these two lines will do. key, value = line.strip().split(":", 1) d[key] = value – meteor23 Apr 17 '17 at 13:20