简体   繁体   English

如何使用Python连续读取基于Linux的操作系统的CPU温度?

[英]How can I get a continuous reading of CPU temperature for Linux based operating systems using Python?

I'm trying to make a program for raspberry pi, but I'm continuously switching between Mac and Raspberry Pi. 我正在尝试为树莓派制作程序,但我一直在Mac和树莓派之间进行切换。 Is there a way to access CPU Temp through Linux using Python. 有没有一种方法可以使用Python通过Linux访问CPU Temp。 And can I make it work with tkinter ? 我可以使其与tkinter吗? ( tkinter being unable to properly use while loops from my knowledge (据我所知tkinter无法正确使用while循环

# How can I get a continuous CPU temperature reading for Linux (Mac//Raspberry Pi) using a 
def function():
    #stuff
    tkinterFrame.after(delay, function)
# im using tkinter so avoiding while loops
# need to use function .after()```

I expect a continuous output that refreshes every second.

Linux gives you the current temperature of the CPU when you read the file /sys/class/thermal/thermal_zone0/temp . 当您读取文件/sys/class/thermal/thermal_zone0/temp时,Linux会为您提供CPU的当前温度。 You will get a single line of text with the temperature as an Integer . 您将获得一行文本,温度为Integer So you have to divide the result by 1000 to get the temperature in °C . 因此,您必须将结果除以1000才能获得以°C为单位的温度。 Please take a look at this simple example which read the current time and the temperature to print both in the terminal. 请看一下这个简单的示例,该示例读取当前时间和温度以在终端上进行打印。

import time
import datetime

while(True):
    CurrentTime = datetime.datetime.now()

    with open(r"/sys/class/thermal/thermal_zone0/temp") as File:
        CurrentTemp = File.readline()

    print(str(CurrentTime) + " - " + str(float(CurrentTemp) / 1000))

    time.sleep(1)

All you have to do now is to store the results and print them (maybe with a plot?). 您现在要做的就是存储结果并打印出来(也许有图吗?)。 You can use an extra thread to do it, so your application won´t be stuck when you use some kind of delay (because you don´t need to read the temperature every millisecond - every second is enough I think). 您可以使用一个额外的线程来执行此操作,因此当您使用某种延迟时,您的应用程序不会卡住(因为您不需要每毫秒读取一次温度-我认为每一秒钟就足够了)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM