I have weather(json) data from api. I want to display only a part of it which I put in a dictionary:
vals = {
'temperature': 34.41,
'summary': 'Clear',
'ozone': 249.95,
'humidity': 0.32,
'precipType': 'rain',
'pressure': 1010.05,
'dewPoint': 15.31,
'time': 1456393033,
'windSpeed': 2.5,
'apparentTemperature': 34.23,
'icon': 'clear-day',
'windBearing': 96,
'precipProbability': 0.01,
'cloudCover': 0.17,
'precipIntensity': 0.0203
}
I use this code to display the notification in the format of 'key: value'. Code follows:
for i in sorted(vals.keys()):
if i == 'time':
vals[i] = datetime.datetime.fromtimestamp(int(vals[i])) #unix timestamp to readble format
if i == 'summary':
continue #Put it in the notif's title not body
msg = msg + str(i).strip() + ':\ ' +str(vals[i]).strip() + '\n'
msg = 'notify-send -u critical ' + vals['summary'] + ' ' + msg
os.system(msg)
The out displays a notification with the title(in this case, the summary- 'Clear') and the first key:value pair i.e. apparentTemperature: 34.23 and then the terminal shows the following error:
sh: 2: cloudCover: 0.17: not found
sh: 3: dewPoint: 15.31: not found
sh: 4: humidity: 0.32: not found
sh: 5: icon: clear-day: not found
sh: 6: ozone: 249.95: not found
sh: 7: precipIntensity: 0.0203: not found
sh: 8: precipProbability: 0.01: not found
sh: 9: precipType: rain: not found
sh: 10: pressure: 1010.05: not found
sh: 11: temperature: 34.41: not found
sh: 12: time: 2016-02-25: not found
sh: 13: windBearing: 96: not found
sh: 14: windSpeed: 2.5: not found
What is the error and how do I rectify it?
The error is in msg = 'notify-send -u critical ' + vals['summary'] + ' ' + msg. Your sh thinks that arguments vals['summary'] and msg are commands to execute by sh. It happens because of spaces in the output of your msg (I`m not telling you about confusion related to same names of your msg-variables).
You can avoid it using quotes (\") in your output data. So msg can looks like
msg = 'notify-send -u critical \"%s %s\"' %% (vals['summary'], msg)
or
msg = 'notify-send -u critical ' + '\"' + vals['summary'] + ' ' + msg + '\"'
UPD I don`t understand the main question before, so:
There are some troubles using multiline notify-send in scripts. The easiest way, I think, is to use echo -e in your script, for example:
notify-send "Title" "$(echo -e "This is the first line.\nAnd this is the second.")"
You can try to use this thought in your script, but you have to do some tricks with quotes and control characters.