所以我試圖創建一個通過Volumio的REST API(文檔在這裏:https://volumio.github.io/docs/API/REST_API.html)與音樂服務器Volumio交互的小程序。基本上,我的程序應該將命令作爲輸入,將其翻譯爲REST API請求,發送請求並打印出歌曲的狀態和標題。我承認在這裏輸入一個無效的命令是有空間的,但目前它不是我關心的問題。我擔心輸入命令後的輸出是錯誤的。下面是代碼:Python:在循環內更新
import json
import requests
def controls(cmd):
volumio = requests.get("http://volumio.local:3000/api/v1/getstate")
vol_data = volumio.text
py_data = json.loads(vol_data)
if cmd == 'getstate':
print(py_data['title'], py_data['status'])
else:
requests.get("http://volumio.local:3000/api/v1/commands/?cmd=%s" % cmd)
print(py_data['title'], py_data['status'])
while True:
input = raw_input('Command: ')
controls(input)
基本上,提交例如命令 '暫停' 後,輸出應該是:
(u'04 - The Woods.mp3', u'pause')
然後在「再次play'ing:
(u'04 - The Woods.mp3', u'play')
'next'應該簡單地改變歌曲名稱並保持相同的狀態。但這裏是我的輸出,當我運行:
Command: play
(u'04 - The Woods.mp3', u'pause')
Command: play
(u'04 - The Woods.mp3', u'play') #showing the state from line 1 command
Command: getstate
(u'04 - The Woods.mp3', u'play') #shows correct updated state
Command: next
(u'04 - The Woods.mp3', u'play') #showing wrong song title
Command: getstate
(u'A.T.A.B.', u'play') #updated and showing correct song title from line 7
Command: pause
(u'A.T.A.B.', u'play')
Command: play
(u'A.T.A.B.', u'pause')
Command:
我的輸出似乎是一個循環的背後,我想不通爲什麼。
嗨,因爲你正在讀取第二個requests.get()之前設置的py_data。從第二個requests.get的結果被扔掉,因爲沒有變量分配返回值 – Nick