Search code examples
python-2.7dictionaryraspberry-pisubprocessvolumio

Python 2.7.9 subprocess convert check_output to dictionary (volumio)


I've been searching a long time, but I can't find an answer. I'm making a script for volumio on my Raspberry Pi

In the terminal, when I type

volumio status

I get exactly

{
  "status": "pause",
  "position": 0,
  "title": "Boom Boom",
  "artist": "France Gall",
  "album": "Francegall Longbox",
  "albumart": "/albumart?cacheid=614&web=France%20Gall/Francegall%20Longbox/extralarge&path=%2FUSB&metadata=false",
  "uri": "/Boom Boom.flac",
  "trackType": "flac",
  "seek": 21192,
  "duration": 138,
  "samplerate": "44.1 KHz",
  "bitdepth": "16 bit",
  "channels": 2,
  "random": true,
  "repeat": null,
  "repeatSingle": false,
  "consume": false,
  "volume": 100,
  "mute": false,
  "stream": "flac",
  "updatedb": false,
  "volatile": false,
  "service": "mpd"
}

In python, I would like to store this in a dictionary

since it already has the right formatting, I thought that assigning it to a variable will make it a dictionnary right away as follows:

import subprocess, shlex
cmd = "volumio status | sed -e 's/true/True/g' -e 's/false/False/g' -e 's/null/False/g'"
cmd = shlex.split(cmd)
status = subprocess.check_output(cmd)

print status["volume"]

If what I thought was true I would get "100". Instead, I get this error :

File "return.py", line 7, in <module>
    print status["volume"]
TypeError: string indices must be integers, not str

this means "status" is stored as a string. Does anybody know how I can make it a dictionary?

dict() doesn't make it, i get :

ValueError: dictionary update sequence element #0 has length 1; 2 is required

Solution

  • Victory! I was able to make my code work with eval()

    import subprocess
    
    status = subprocess.check_output("volumio status | sed -e 's/true/True/g' -e 's/false/False/g' -e 's/null/False/g'", shell=True)
    status = eval(status)
    print status["volume"]
    

    it returns 100