python
import os
import time
import sys
import select
def get_cpu_temp():
# 讀取系統溫度資訊
res = os.popen('vcgencmd measure_temp').readline()
return res.replace("temp=", "").replace("'C\n", "")
def is_data():
# 檢查是否有鍵盤輸入
return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
if __name__ == '__main__':
try:
print("按下任何鍵結束程序...")
while True:
if is_data():
sys.stdin.read(1)
break
# 獲取並打印 CPU 溫度
temp = get_cpu_temp()
print(f"CPU Temperature: {temp}°C")
time.sleep(1) # 每秒更新一次
except KeyboardInterrupt:
print("\n程序已被手動終止")
確保使用這個新的程式碼,它不需要 keyboard 模塊。如果你在執行時仍然遇到問題,請檢查是否保存了正確的 Python 文件並且在終端機中執行了正確的文件。這段程式碼應該不會提到 keyboard 模塊。
確保將以上的代碼保存到一個 Python 文件中,例如命名為 cpu_temp.py。
在樹莓派的終端機中運行:
bash
複製程式碼
python cpu_temp.py
這個程序應該可以正常運行,顯示 CPU 溫度,並在按下任何鍵時終止。如果你遇到其他錯誤,請提供詳細信息,我可以幫助進一步調試。
ChatGPT