我有来自api的天气(json)数据。我想只显示我放在字典中的一部分:
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
}
我使用此代码以'key:value'格式显示通知。代码如下:
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)
out显示带有标题的通知(在本例中为摘要 - 'Clear')和第一个键:值对,即apparentTemperature:34.23,然后终端显示以下错误:
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
错误是什么,如何纠正?
答案 0 :(得分:1)
错误在msg = 'notify-send -u critical ' + vals['summary'] + ' ' + msg
。您的sh
认为参数vals['summary']
和msg
是sh
执行的命令。这是因为msg
输出中的空格(我没有告诉您与msg
- 变量的相同名称相关的混淆)。
您可以在输出数据中使用引号(\"
)来避免它。所以msg
看起来像
msg = 'notify-send -u critical \"%s %s\"' %% (vals['summary'], msg)
或
msg = 'notify-send -u critical ' + '\"' + vals['summary'] + ' ' + msg + '\"'
<强> UPD 强> 我之前不理解主要问题,所以:
在脚本中使用多行notify-send
会遇到一些麻烦。我认为最简单的方法是在脚本中使用echo -e
,例如:
notify-send "Title" "$(echo -e "This is the first line.\nAnd this is the second.")"
你可以尝试在你的脚本中使用这个想法,但是你必须用引号和控制字符做一些技巧。