我正在爲使用weather.com的api提取數據的python編寫我的Raspberry Pi的天氣顯示程序。就目前來看,我已經在每個主'while'循環後將它設置爲休眠5分鐘。這是因爲我不希望Pi經常使用WiFi來獲取相同的天氣數據。這個問題是,如果我嘗試以任何方式關閉或更改程序,它會在繼續之前等待完成time.sleep()函數。我想添加按鈕來創建一個滾動菜單,但目前,程序將在繼續之前掛在time.sleep()函數中。有沒有其他方法可以用來延遲數據的提取,同時保持程序響應?python time.sleep()提取網頁內容的替代方案
0
A
回答
1
你可以做這樣的事情:
import time, threading
def fetch_data():
# Add code here to fetch data from API.
threading.Timer(10, fetch_data).start()
fetch_data()
則fetch_data方法將一個線程中執行,所以你不會有太大的問題。調用該方法之前還有一段延遲。所以你不會轟炸API。
0
與Python的time
模塊
import time
timer = time.clock()
interval = 300 # Time in seconds, so 5 mins is 300s
# Loop
while True:
if timer > interval:
interval += 300 # Adds 5 mins
execute_API_fetch()
timer = time.clock()
+0
它不起作用 - 它只等待5分鐘一次 - 不定期 – furas
0
Pygame的具有pygame.time.get_ticks()
,你可以用它來檢查時間,並用它在主循環執行函數創建一個定時器。
import pygame
# - init -
pygame.init()
screen = pygame.display.set_mode((800, 600))
# - objects -
curr_time = pygame.time.get_ticks()
# first time check at once
check_time = curr_time
# - mainloop -
clock = pygame.time.Clock()
running = True
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# - updates -
curr_time = pygame.time.get_ticks()
if curr_time >= check_time:
print('time to check weather')
# TODO: run function or thread to check weather
# check again after 2000ms (2s)
check_time = curr_time + 2000
# - draws -
# empty
# - FPS -
clock.tick(30)
# - end -
pygame.quit()
順便說一句:如果抓取web內容需要更多時間,然後在線程中運行它。
相關問題
- 1. UIWebView豐富內容的替代方案?
- 2. 提取網頁內容
- 3. cUrl替代方案在網頁上獲取POST答案
- 4. 替代time.sleep()
- 5. python-mathdom的替代方案
- 6. Python的shlex.split替代方案
- 7. 發佈提取數據替代方案()
- 8. 後臺提取替代方案
- 9. Python GeoModel替代方案
- 10. 提供替代Flash內容
- 11. 從網頁中提取內容
- 12. 從網頁提取內容數據
- 13. 與gsl兼容的gmp替代方案
- 14. 網頁抓取動態內容與Python
- 15. Python中的multiprocessing.manager的替代方案
- 16. 提供角度2的替代方案?
- 17. C++標準容器提升ptr_array的替代方案
- 18. 表的替代方案:網格列表
- 19. 手機網站ImageMap的替代方案
- 20. Python GD GD庫的替代方案
- 21. Python/if語句的替代方案
- 22. Python是否有JGraph的替代方案?
- 23. DYLD_LIBRARY_PATH/LD_LIBRARY_PATH的替代方案
- 24. cin.ignore替代方案,清除緩衝區中的所有內容
- 25. 用於嵌入活動外部內容的iframe替代方案
- 26. ipython的atexit替代方案
- 27. Bouncy Castle JCE提供商替代方案
- 28. scipy.stats.norm.pdf的替代方案?
- 29. scipy.cluster.hierarchy.cut_tree()的替代方案
- 30. DefaultDict的替代方案
你不清楚你在問什麼,你可能想寫一個[MCVE]來演示你遇到的問題。 – pvg
你可以減少睡眠時間到1秒,並把它放在一個循環中:'for my in xrange(300):time.sleep(1)'。 –
'pygame'有'pygame.time',你可以使用'pygame.time'來檢查時間並在'while True'循環中執行命令。 – furas