我想做的事情是這樣的。我想每小時運行以下函式,持續24小時。這個函式從一個api中收集資料,將數值附加到一個字典中,并將其保存為一個json檔案供以后使用。我正在運行的代碼作業正常,但它并不優雅,因為我必須用鍵盤中斷來停止它。我想讓腳本在24小時后停止運行,并在每個小時列印。print('data successfully collected at ' time.ctime()
def weather_collect():
url = 'http://api.openweathermap.org/data/2.5/weather?lat={}& lon={}& appid={}& units=metric'
response = requests.get(url.format(lat,lon, api_key)
r = response.json()
data['temperature'].append(r['main']['temp'] )
data['humidity'].append(r['main']['humidity'] )
data['pressure'].append(r['main']['pressure'] )
data['visibility'].append(r['visibility'] )
data['wind_speed'].append(r['wind']['speed'] )
data['time'].append(time.ctime() )
with open('data.json', 'w') as f:
f.write(json.dumps(data))
return data
schedule.every(1).hour.do(weather_collect)
while 1:
schedule.run_pending()
time.sleep(1)
uj5u.com熱心網友回復:
一個解決方案可能是添加一個計數器,每次回圈執行時,你都會遞增1。 并在第24次迭代時中斷 "while 1 "回圈。
uj5u.com熱心網友回復:
代替:
schedule.every(1) .hour.do(weather_collect)
while 1:
schedule.run_pending()
time.sleep(1)
把這個:
for i in range(25)。
天氣_收集()
print('data successfully collected at ' time.ctime())
sleep(3600) # sleep one hour。
退出()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/328085.html
標籤:
上一篇:無法解決單元測驗中的引數'Volo.Abp.Identity.IIdentityRoleRepositoryroleRepository'。
