精华内容
下载资源
问答
  • Linux下获取cpu温度

    2021-08-11 10:20:31
    大致strace跟踪了sensors命令,发现是读取类似/sys/class/hwmon/hwmon1/temp1_input中的值,再结合google的如下几篇文章: https://www.kernel.org/doc/Documentation/hwmon/sysfs-interface 总结如下: # ...

    大致strace跟踪了下sensors命令,发现是读取类似/sys/class/hwmon/hwmon1/temp1_input中的值,再结合google下的如下几篇文章:

    https://www.kernel.org/doc/Documentation/hwmon/sysfs-interface

    总结如下:

    # ls -al /sys/class/hwmon/
    total 0
    drwxr-xr-x  2 root root 0 Aug 11 10:09 .
    drwxr-xr-x 64 root root 0 Aug 11 10:09 ..
    lrwxrwxrwx  1 root root 0 Aug 11 10:09 hwmon0 -> ../../devices/platform/coretemp.0/hwmon/hwmon0
    lrwxrwxrwx  1 root root 0 Aug 11 10:09 hwmon1 -> ../../devices/platform/coretemp.1/hwmon/hwmon1
    lrwxrwxrwx  1 root root 0 Aug 11 10:09 hwmon2 -> ../../devices/LNXSYSTM:00/device:00/ACPI000D:00/hwmon/hwmon2

    可以发现hwmon0目录是cpu0的温度监测,hwmon1是cpu1的温度

    注意下,这个对应关系不同机器不一样,同时重启后该对应关系也可能会变化。

    再进入目录:

    # cat /sys/class/hwmon/hwmon0/temp1_input 
    33000
    # cat /sys/class/hwmon/hwmon0/temp2_input 
    31000
    # sensors
    coretemp-isa-0000
    Adapter: ISA adapter
    Physical id 0:  +33.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 0:         +31.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 1:         +27.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 2:         +28.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 3:         +30.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 4:         +27.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 8:         +30.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 9:         +29.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 10:        +30.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 11:        +28.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 12:        +31.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 16:        +26.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 17:        +29.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 18:        +26.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 19:        +29.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 20:        +31.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 24:        +28.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 25:        +28.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 26:        +28.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 27:        +28.0°C  (high = +87.0°C, crit = +97.0°C)
    Core 28:        +29.0°C  (high = +87.0°C, crit = +97.0°C)

    temp1_input对应的是整个cpu的温度

    temp1_input对应的是core0,temp2_input对应的是core1,依次类推。

    展开全文
  • 嵌入式Linux下获取CPU温度方法

    千次阅读 2020-07-31 00:21:23
    本文描述嵌入式linux下获取cpu温度的方法。

    1 前言

      嵌入式设备中,对于长时间工作的设备,特别是工控产品,一般会增加一个风扇为cpu主动散热。而风扇一般会选用可调速的,这样程序可以根据cpu温度实时调整风扇速度,以达到高温时能及时降低cpu温度,低温时节约功耗的目的。


    2 获取cpu温度

      cpu原厂提供的linux内核通常已经带有cpu温度检测驱动,并将温度信息映射到用户文件系统下,用户只需从该虚拟文件读取温度信息即可。cpu温度虚拟文件位于“/sys/devices/virtual/thermal”或者“/sys/class/thermal”下,命名为“thermal_zoneX”,X表示cpu核温度检测节点,如果是多核cpu通常会有多个温度检测节点;使用其中一个即可,因为温度通常差异不大。


    rk3399 ubuntu16 下cup核温度节点

    root@firefly:/home# ls /sys/devices/virtual/thermal/
    cooling_device0  cooling_device1  cooling_device2  thermal_zone0  thermal_zone1
    root@firefly:/home# ls /sys/class/thermal/
    cooling_device0  cooling_device1  cooling_device2  thermal_zone0  thermal_zone1
    

    2.1 通过shell获取

    root@firefly:/home# cat /sys/class/thermal/thermal_zone0/temp
    42222
    root@firefly:/home# cat /sys/class/thermal/thermal_zone1/temp
    41666
    

    其中温度单位是0.001℃,即是温度节点0“thermal_zone0”当前温度为42.222℃。


    2.2 通过watch实时刷新

      通过watch命令,每2秒读取一次cpu温度输出到终端。

    root@firefly:/home# watch -n 2 -d echo cpu temperature:[$(cat /sys/class/thermal/thermal_zone0/temp)]
    Every 2.0s: echo cpu temperature:[42777]                                                                       Thu Jul 30 16:02:05 2020
    cpu temperature:[42777]
    

    2.3 通过C语言读取

    #include <stdio.h>   
    #include <unistd.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    
    #define CPU_TEMP_FILE0	"/sys/devices/virtual/thermal/thermal_zone0/temp"
    #define CPU_TEMP_FILE1	"/sys/devices/virtual/thermal/thermal_zone0/temp"
    
    int main(int arc, char *argv[])
    {
    	FILE *fp = NULL;
    	int temp = 0;
    	
    	fp = fopen (CPU_TEMP_FILE0, "r");
    	if (fp < 0)
    	{
    		printf("open file failed,%s\n", strerror(errno));
    	}
    	for (;;)
    	{
    		fscanf(fp, "%d", &temp);
    		printf("cpu temperature: [%d.%d C]\n", temp/1000, temp%1000/100);
    		sleep(2);
    	}
    	fclose(fp);
    	return 0;
    }
    

    编译执行

    root@firefly:/home# gcc cpu_temp.c -o cpu_temp
    root@firefly:/home# ./cpu_temp
    cpu temperature: [42.7 C]
    cpu temperature: [42.7 C]
    cpu temperature: [42.7 C]
    
    展开全文
  • 最近要在windows下获取CPU的温度信息,网上有些介绍CPU温度获取方法的文档,也有VS的源代码,但是运行后总是显示固定的100度,我的开发环境是Qt5.9.9, 64位的win10,四核CPU,由于无法等待、时间紧急,只能自己动手...
  •  psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率(包括CPU、内存、磁盘、网络等)信息。它主要应用于系统监控,分析和限制系统资源及进程的管理。它实现...

    方法一:

            psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率(包括CPU、内存、磁盘、网络等)信息。它主要应用于系统监控,分析和限制系统资源及进程的管理。它实现了同等命令行工具提供的功能,如ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice、ionice、iostat、iotop、uptime、pidof、tty、taskset、pmap等。目前支持32位和64位的Linux、Windows、OS X、FreeBSD和Sun Solaris等操作系统(参考https://www.cnblogs.com/liu-yao/p/5678157.html)

    root@h36:~# python
    Python 2.7.9 (default, Jun 29 2016, 13:08:31) 
    [GCC 4.9.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import psutil
    >>> psutil.virtual_memory().percent	#内存的占用率
    54.9
    >>> psutil.disk_partitions(all=False)	#磁盘分区信息
    [sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,relatime,errors=remount-ro,data=ordered'), sdiskpart(device='/dev/sda7', mountpoint='/tmp', fstype='ext4', opts='rw,relatime,data=ordered'), sdiskpart(device='/dev/sda8', mountpoint='/home', fstype='ext4', opts='rw,relatime,data=ordered'), sdiskpart(device='/dev/sda5', mountpoint='/var', fstype='ext4', opts='rw,relatime,data=ordered')]
    >>> psutil.disk_usage("/").percent	#磁盘sda1在"/"目录下的使用率
    30.7
    >>> psutil.cpu_percent(0)	#本机cpu的总占用率
    0.6
    >>> psutil.cpu_percent(percpu=True) #每个CPU每核的使用率,我这里的虚拟机是双CPU双核
    [0.1, 0.2, 0.0, 0.0]
    >>> psutil.sensors_temperatures()
    {'coretemp': [shwtemp(label='Physical id 0', current=100.0, high=100.0, critical=100.0), shwtemp(label='Core 0', current=100.0, high=100.0, critical=100.0), shwtemp(label='Core 1', current=100.0, high=100.0, critical=100.0), shwtemp(label='Physical id 1', current=100.0, high=100.0, critical=100.0), shwtemp(label='Core 0', current=100.0, high=100.0, critical=100.0), shwtemp(label='Core 1', current=100.0, high=100.0, critical=100.0)]}

    疑惑:在命令行中执行以上命令CPU使用率都正常,可是写入py脚本(print(psutil.cpu_percent(0)))文件后执行却不是0.0就是100.0,奇了怪了

    解决:虽然在命令行中psutil.cpu_percent(0)能出正常结果,但是上面那个疑惑在脚本里还必须不能使用0,比如写成psutil.cpu_percent(1)才能解决上面的问题,这个参数是时间间隔多少秒获取CPU使用率。

    注:在使用psutil模块时要注意版本大小,一开始我在Debian8.6下用apt-get install pustil直接装后咋也获取不了CPU温度,虽然按官方网站https://pypi.python.org/pypi/psutil#downloads在命令行下执行psutil.sensors_temperatures()却报错,后来我才意识到了有可能是版本过低的问题,于是去下载了较新的psutil 5.4.2才解决了问题(也可以不去官网下载psutil 5.4.2tar包,应该用pip安装,它就会去自动下载最新了psutil版本了,挺省事的倒是。先执行apt-get install python-pip安装pip,用pip install psutil之前可能还需要重要的一步apt-get install python-dev,否则会报错:

    psutil/_psutil_common.c:9:20: fatal error: Python.h: No such file or directory
    
     #include <Python.h>
    
                        ^


    补充(代码来自http://blog.51cto.com/dgd2010/1868851):Python获取网卡信息(名称、MAC、IP、网关等)

    Python pypi库中一个模块名字叫“netifaces”,使用C语言写的一个第三方模块。可以:
    1.获取本机的所有网关
    2.获取本机所有的接口Interface(网卡NIC)
    3.获取本机指定接口的详细信息,包括IP地址、子网掩码、广播地址、MAC地址等

    #!/usr/bin/python
    # encoding: utf-8
    # -*- coding: utf8 -*-
    """
    Created by PyCharm.
    File:               LinuxBashShellScriptForOps:getNetworkStatus.py
    User:               Guodong
    Create Date:        2016/11/2
    Create Time:        16:20
     
    show Windows or Linux network Nic status, such as MAC address, Gateway, IP address, etc
    """
    
    import os
    import sys
     
    try:
        import netifaces
    except ImportError:
        try:
            command_to_execute = "pip install netifaces || easy_install netifaces"
            os.system(command_to_execute)
        except OSError:
            print "Can NOT install netifaces, Aborted!"
            sys.exit(1)
        import netifaces
     
    routingGateway = netifaces.gateways()['default'][netifaces.AF_INET][0]
    routingNicName = netifaces.gateways()['default'][netifaces.AF_INET][1]
     
    for interface in netifaces.interfaces():
        if interface == routingNicName:
            # print netifaces.ifaddresses(interface)
            routingNicMacAddr = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]['addr']
            try:
                routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
                # TODO(Guodong Ding) Note: On Windows, netmask maybe give a wrong result in 'netifaces' module.
                routingIPNetmask = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['netmask']
            except KeyError:
                pass
     
    display_format = '%-30s %-20s'
    print display_format % ("Routing Gateway:", routingGateway)
    print display_format % ("Routing NIC Name:", routingNicName)
    print display_format % ("Routing NIC MAC Address:", routingNicMacAddr)
    print display_format % ("Routing IP Address:", routingIPAddr)
    print display_format % ("Routing IP Netmask:", routingIPNetmask)
    
    运行结果:
    # python getNetworkStatus.py
    Routing Gateway:               10.6.28.254
    Routing NIC Name:              eth0
    Routing NIC MAC Address:       06:7f:12:00:00:15
    Routing IP Address:            10.6.28.28

    Routing IP Netmask:            255.255.255.0

    获取ip还有种写法:

    import socket
    import fcntl
    import struct
    
    def get_ip_address(ifname): 
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
        print socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) 
    
    get_ip_address('lo')
    get_ip_address('eth0')

    运行结果:

    127.0.0.1
    10.6.28.28

    >>> import netifaces
    >>> netifaces.interfaces()
    [u'lo', u'eth0', u'eth1', u'eth2']
    >>> psutil.net_io_counters(pernic=True)
    {'lo': snetio(bytes_sent=141053, bytes_recv=141053, packets_sent=1411, packets_recv=1411, errin=0, errout=0, dropin=0, dropout=0), 'eth2': snetio(bytes_sent=74862, bytes_recv=16424, packets_sent=920, packets_recv=81, errin=0, errout=0, dropin=0, dropout=0), 'eth1': snetio(bytes_sent=126292, bytes_recv=34980, packets_sent=1515, packets_recv=174, errin=0, errout=0, dropin=0, dropout=0), 'eth0': snetio(bytes_sent=21560891, bytes_recv=1316735948, packets_sent=164194, packets_recv=1119225, errin=0, errout=0, dropin=0, dropout=0)}
    >>> print(netifaces.interfaces()[2])
    eth1
    >>> print(psutil.net_io_counters(pernic=True)["lo"][0])
    141053

    小综合:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import json, os, time, psutil, netifaces
    
    def GetCPUorDiskTemper(type='Core'):
        dict_cpu_temp = {}
        if hasattr(psutil, "sensors_temperatures"):
            temps = psutil.sensors_temperatures()
        else:
            temps = {}
        cpu_each = []
        names = list(temps.keys())
        for name in names:
            if name in temps:
                for entry in temps[name]:
                    if type in entry.label:
                        dict_cpu_temp[entry.label] = entry.current
                        cpu_each.append(dict_cpu_temp[entry.label])
        cpu_top = sorted(dict_cpu_temp.items(),key=lambda d:d[0])[0][1]
        return {"cpu_top":cpu_top,"cpu_each":cpu_each}
    
    def GetCPUInfo():
        cpu_t = GetCPUorDiskTemper()["cpu_each"]
        cpu_num = int(os.popen("cat /proc/cpuinfo| grep 'physical id'| sort| uniq| wc -l").readline().strip())
        numb = os.popen("cat /proc/cpuinfo| grep 'cpu cores'| uniq").readline()
        cpucore_num = int(numb[12:-1])
        cpu_u = psutil.cpu_percent(percpu=True,interval=1)
        cpu = []
        cpu1 = {}
        list = {}
        y = 1
        z = 0
        data = []
        for i in range(0,len(cpu_u)):
            list = {"corename":"Core "+str(z),"cpu_u":cpu_u[i],"cpu_t":cpu_t[i]}
            z = z + 1
            data.append(list)
            if i+1 == cpucore_num*y:
                cpu1["data"] = data
                cpu1["cpuname"] = "cpu "+str(y-1)
                y = y + 1
                cpu.append(cpu1)
                cpu1 = {}
                data = []
                z = 0
        return cpu
    
    def GetNetwork():
        net = []
        for i in range(1,len(netifaces.interfaces())):
            netname = str(netifaces.interfaces()[i])
            bytes_sent = int(psutil.net_io_counters(pernic=True)[netname][0])
            bytes_recv = int(psutil.net_io_counters(pernic=True)[netname][1])
            eth_status = os.popen('sudo ethtool '+netname).readlines()[-1][16:-1]
            x = {"name":netname,"eth_status":eth_status,"bytes_sent":bytes_sent,"bytes_recv":bytes_recv}
            net.append(x)
        return net
        
    total = 0
    used = 0
    disk_partitions = psutil.disk_partitions(all=False)
    for i in range(0,len(disk_partitions)):
        partition = disk_partitions[i][1]
        total_each = psutil.disk_usage(partition)[0]
        total = total + total_each
        used_each = psutil.disk_usage(partition)[1]
        used = used + used_each
    disk_u = used/float(total)*100
    cpu_u = psutil.cpu_percent(1)
    cpu_t = GetCPUorDiskTemper()["cpu_top"]
    memory_u = psutil.virtual_memory().percent
    boot_time = psutil.boot_time()
    runtime = os.popen('cat /proc/uptime').readlines()[0].split(" ")[0]
    data = {"a":{"disku":disk_u,"memu":memory_u,"cpuu":cpu_u,"cput":cpu_t,"boot_time":boot_time,\
            "runtime":runtime},"b":GetNetwork(),"c":GetCPUInfo()}
    print(data)

    运行结果:

    {'a': {'cput': 100.0, 'cpuu': 0.2, 'disku': 29.98913391327393, 'memu': 40.5, 'boot_time': 1514893852.0, 'runtime': '89424.57'}, 'c': [{'cpuname': 'cpu 0', 'data': [{'corename': 'Core 0', 'cpu_t': 100.0, 'cpu_u': 1.0}, {'corename': 'Core 1', 'cpu_t': 100.0, 'cpu_u': 0.0}]}, {'cpuname': 'cpu 1', 'data': [{'corename': 'Core 0', 'cpu_t': 100.0, 'cpu_u': 0.0}, {'corename': 'Core 1', 'cpu_t': 100.0, 'cpu_u': 0.0}]}], 'b': [{'eth_status': 'yes', 'bytes_sent': 404589707, 'name': 'eth0', 'bytes_recv': 200725324}, {'eth_status': 'yes', 'bytes_sent': 71170, 'name': 'eth1', 'bytes_recv': 50232}, {'eth_status': 'yes', 'bytes_sent': 80868, 'name': 'eth2', 'bytes_recv': 48402}]}


    方法二:(不建议使用,方法一完全就够用而且还好。而且算的结果还和方法一不一样,我感觉方法一更准确一些吧)

    直接上代码:hui.py

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    import os, time, re, sensors
    
    last_worktime=0
    last_idletime=0
    
    sensors.init()
    
    def get_mem_usage_percent():
        try:
            f = open('/proc/meminfo', 'r')
            for line in f:
                if line.startswith('MemTotal:'):
                    mem_total = int(line.split()[1])
                elif line.startswith('MemFree:'):
                    mem_free = int(line.split()[1])
                elif line.startswith('Buffers:'):
                    mem_buffer = int(line.split()[1])
                elif line.startswith('Cached:'):
                    mem_cache = int(line.split()[1])
                elif line.startswith('SwapTotal:'):
                    vmem_total = int(line.split()[1])
                elif line.startswith('SwapFree:'):
                    vmem_free = int(line.split()[1])
                else:
                    continue
            f.close()
        except:
            return None
        physical_percent = usage_percent(mem_total - (mem_free + mem_buffer + mem_cache), mem_total)
        virtual_percent = 0
        if vmem_total > 0:
            virtual_percent = usage_percent((vmem_total - vmem_free), vmem_total)
        return physical_percent, virtual_percent
    
    def usage_percent(use, total):
        try:
            ret = (float(use) / total) * 100
        except ZeroDivisionError:
            raise Exception("ERROR - zero division error")
        return ret
    
    def disk_use():
        statvfs = os.statvfs('/')
        total_disk_space = statvfs.f_frsize * statvfs.f_blocks
        free_disk_space = statvfs.f_frsize * statvfs.f_bfree
        disk_usage = (total_disk_space - free_disk_space) * 100.0 / total_disk_space
    #    disk_tip = "硬盘空间使用率:"+str(disk_usage)+"%"
    #    print(disk_tip)
        return disk_usage
    
    def mem_use():
        mem_usage = get_mem_usage_percent()
        mem_usage = mem_usage[0]
    #    mem_tip = "物理内存使用率:"+str(mem_usage)+"%"
    #    print(mem_tip)
        return mem_usage
        
    def cpu_use():
        global last_worktime, last_idletime
        f=open("/proc/stat","r")
        line=""
        while not "cpu " in line: line=f.readline()
        f.close()
        spl=line.split(" ")
        worktime=int(spl[2])+int(spl[3])+int(spl[4])
        idletime=int(spl[5])
        dworktime=(worktime-last_worktime)
        didletime=(idletime-last_idletime)
        rate=float(dworktime)/(didletime+dworktime)
        cpu_t = rate*100
        last_worktime=worktime
        last_idletime=idletime
        if(last_worktime==0): return 0
    #    cpu_tip = "CPU使用率:"+str(cpu_t)+"%"
    #    print(cpu_tip)
        return cpu_t
    
    def cpu_temperature():
        for chip in sensors.ChipIterator("coretemp-*"):
            i = 0
            sum = 0
            for feature in sensors.FeatureIterator(chip):
                sfi = sensors.SubFeatureIterator(chip, feature)
                vals = [sensors.get_value(chip, sf.number) for sf in sfi]
                sum = sum + vals[0]
                i = i + 1
    #            cpu_tmp = "CPU温度:"+sum/i+"℃"
    #            print(cpu_tmp)
            return sum/i
    
    disk = disk_use()
    print(disk)
    print(type(disk))
    mem = mem_use()
    print(mem)
    print(type(mem))
    cpua = cpu_use()
    print(cpua)
    print(type(cpua))
    cpub = cpu_temperature()
    print(cpub)
    print(type(cpub))
    sensors.cleanup()
    
    注意:CPU使用率、内存使用率、硬盘使用率都还好说,但是CPU温度就比较麻烦一些了,得使用sensors来整,lm_sensors的软件可以帮助我们来监控主板、CPU的工作电压、风扇转速、温度等数据。这些数据我们通常在主板的BIOS也可以看到。当我们可以在机器运行的时候通过lm_sensors随时来监测着CPU的温度变化,可以预防呵保护因为CPU过热而会烧掉。如果你没有这个模块,使用apt-get install lm-sensors命令来安装即可(我这里使用的是Debian8.6 64位)。

    还得和上面的同一目录下再来这么一个文件(https://github.com/paroj/sensors.py/blob/master/sensors.py)

    运行代码:python hui.py
    32.1816127961
    <type 'float'>
    37.7943290638
    <type 'float'>
    0.251490181586
    <type 'float'>
    100.0
    <type 'float'>

    疑惑:网上还有一种计算CPU使用率的方法,那就是用top命令来获取
    def cpu_use():
        cpu_usage = str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip())
        cpu_tip = "CPU使用率:"+cpu_usage+"%"
        print(cpu_tip)
    但是和我上面的代码结果却不一样,用/proc/stat文件(http://server.51cto.com/sCollege-188250.htm)来计算得到0.252413215089,而用top命令得到的却是0.1

    注:你可能会对这里的CPU温度是100而困惑,执行sensors命令
    root@h36:~# sensors
    coretemp-isa-0000
    Adapter: ISA adapter
    Physical id 0: +100.0°C  (high = +100.0°C, crit = +100.0°C)
    Core 0:        +100.0°C  (high = +100.0°C, crit = +100.0°C)
    为什么会都是100呢?这不科学啊!我这里用的是VMware虚拟机下装的Debian,后来问别人说是这个读不出虚拟机的CPU温度来,至于原因我也不明白,只能读出真实物理机的温度,我试了下的确如此。



    参考:

    http://www.rojtberg.net/836/introducing-sensors-py/

    https://www.cnblogs.com/xuaijun/p/7985147.html

    展开全文
  • Lm_sensors是一个命令行工具,用于显示所有芯片传感器数据的当前读数,包括CPU温度。默认情况,Ubuntu LInux没有安装Lm_Sensors,因此,我们必须自己安装它们。 bob@bob-PC:~$ sudo apt install lm-sensors ...

    Lm_sensors是一个命令行工具,用于显示所有芯片传感器数据的当前读数,包括CPU温度。默认情况下,Ubuntu LInux没有安装Lm_Sensors,因此,我们必须自己安装它们。

    bob@bob-PC:~$ sudo apt install lm-sensors
    

    检测硬件

    接下来,我们需要检测安装在电脑上的硬件监控芯片。现在我们可以开始检测电脑的硬件传感器了:

    bob@bob-PC:~$ sudo sensors-detect
    # sensors-detect revision 6284 (2015-05-31 14:00:33 +0200)
    # System: VMware, Inc. VMware Virtual Platform [None]
    # Board: Intel Corporation 440BX Desktop Reference Platform
    # Kernel: 4.15.0-30Ubuntu-generic x86_64
    # Processor: Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz (6/158/10)
    
    This program will help you determine which kernel modules you need
    to load to use lm_sensors most effectively. It is generally safe
    and recommended to accept the default answers to all questions,
    unless you know what you're doing.
    
    Some south bridges, CPUs or memory controllers contain embedded sensors.
    Do you want to scan for them? This is totally safe. (YES/no): yes
    Silicon Integrated Systems SIS5595...                       No
    VIA VT82C686 Integrated Sensors...                          No
    VIA VT8231 Integrated Sensors...                            No
    AMD K8 thermal sensors...                                   No
    AMD Family 10h thermal sensors...                           No
    AMD Family 11h thermal sensors...                           No
    AMD Family 12h and 14h thermal sensors...                   No
    AMD Family 15h thermal sensors...                           No
    AMD Family 16h thermal sensors...                           No
    AMD Family 17h thermal sensors...                           No
    AMD Family 15h power sensors...                             No
    AMD Family 16h power sensors...                             No
    Intel digital thermal sensor...                             Success!
        (driver `coretemp')
    Intel AMB FB-DIMM thermal sensor...                         No
    Intel 5500/5520/X58 thermal sensor...                       No
    VIA C7 thermal sensor...                                    No
    VIA Nano thermal sensor...                                  No
    
    Some Super I/O chips contain embedded sensors. We have to write to
    standard I/O ports to probe them. This is usually safe.
    Do you want to scan for Super I/O sensors? (YES/no): yes
    
    ..................
    

    显示cpu温度

    可以通过一下命令查看温度数据了:

    bob@bob-PC:~$ sensors
    iwlwifi_1-virtual-0
    Adapter: Virtual device
    temp1:        +33.0°C  
    
    pch_skylake-virtual-0
    Adapter: Virtual device
    temp1:        +38.5°C  
    
    BAT0-acpi-0
    Adapter: ACPI interface
    in0:         +12.45 V  
    
    coretemp-isa-0000
    Adapter: ISA adapter
    Package id 0:  +39.0°C  (high = +100.0°C, crit = +100.0°C)
    Core 0:        +39.0°C  (high = +100.0°C, crit = +100.0°C)
    Core 1:        +38.0°C  (high = +100.0°C, crit = +100.0°C)
    
    thinkpad-isa-0000
    Adapter: ISA adapter
    fan1:           0 RPM
    temp1:        +38.0°C  
    temp2:            N/A  
    temp3:         +0.0°C  
    temp4:         +0.0°C  
    temp5:         +0.0°C  
    temp6:         +0.0°C  
    temp7:         +0.0°C  
    temp8:         +0.0°C  
    
    BAT1-acpi-0
    Adapter: ACPI interface
    in0:         +12.49 V  
    
    acpitz-acpi-0
    Adapter: ACPI interface
    temp1:        +38.0°C  (crit = +128.0°C)
    

    还可以使用watch命令实时关注:

    bob@bob-PC:~$ watch sensors
    

    使用图形化工具psensor显示cpu温度

    使用Psensor,您可以检查以下各项:

    • 主板、CPU传感器和NVidia GPU的温度
    • 硬盘驱动器的温度
    • 风扇的转速
    • 监视CPU使用情况

    最新版本的Psensor还为Ubuntu提供了一个applet指示器,因此在Ubuntu上更容易监控硬件温度。您可以选择在顶部面板中显示温度。它甚至可以在温度超过极限时发送桌面通知。

    我们可以使用下面的命令安装Psensor

    bob@bob-PC:~/Desktop$ sudo apt install -y psensor
    

    打开ubuntu的launchpad,在里面找到psensor,打开该应用就可以看到多个传感器:
    如何在Ubuntu Linux中获取CPU温度如何在Ubuntu Linux中获取CPU温度
    如何在Ubuntu Linux中获取CPU温度如何在Ubuntu Linux中获取CPU温度

    使用图形化工具hardinfo

    Hardinfo是Linux中用于在图形化界面中显示硬件信息的工具。可以使用它检测cpu的温度。以下命令安装hardinfo

    bob@bob-PC:~/Desktop$ sudo apt install hardinfo
    # 运行一下命令打开hardinfo
    bob@bob-PC:~/Desktop$ sudo hardinfo
    

    如何在Ubuntu Linux中获取CPU温度如何在Ubuntu Linux中获取CPU温度

    总结

    在本教程中,我们将学习如何从命令行和桌面获取Ubuntu Linux上的CPU温度。

    展开全文
  • Linux系统获取CPU温度

    2018-08-28 10:28:00
    Linux系统获取CPU温度 摘自:... ...各位好,本篇将简单介绍如何在不同系列的linux操作系统下获取cpu温度。下面我们一一介绍。 工具/原料 centos7系统 debian系统 ...
  • 可以通过读取如下路径中的数据来获取cpu温度信息,不过读取的数据没有经过处理。 cpu0: cat /sys/class/thermal/thermal_zone0/temp cpu1: cat /sys/class/thermal/thermal_zone1/temp 通过命令行的...
  • #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/sysinfo.h> //#include <...typedef struct CPU_PACKED { char name[20]; unsigned int...
  • 第一版 import time import threading from PyQt5.QtCore import QObject, ... sign_cpu_info = pyqtSignal(float, dict) # temp, usage def __init__(self, data_cb): super().__init__() self._data_cb = data_cb
  • 主要介绍了linux系统使用python获取cpu信息脚本,大家参考使用吧
  • go读取Linux下cpu占用率、cpu温度、内存占用率及磁盘占用率
  • 获取CPU温度(总结)

    热门讨论 2014-07-10 08:57:03
    2. 最重要的是参考Intel手册通过读取MSR来读取DTS(Digital Thermal Senser)的值来获取CPU温度 3. 大概讲述了通过WMI,Win32_TemperatureProbe Class,以及WinIO的方式 4. 资源包中包括:Win32_TemperatureProbe ...
  • cpu0:cat /sys/class/thermal/thermal_zone0/tempcpu1:cat ...就会获取cpu当前温度,在我的目录还有一个文件夹 “thermal_zone1”可能是cpu是双核的所以有两个温度 转载于:https://www.cnblogs.com/super-ag...
  • 用驱动获取cpu温度

    千次下载 热门讨论 2013-05-31 20:01:54
    用驱动获取cpu温度,针对intel的cpu
  • RHEL,Centos,Fedora系列安装: $ sudo yum install lm_sensors 查看: $ sudo sensors-detect $ sensors Debian,Ubuntu系列 安装 $ sudo apt-get install lm-sensors 查看 $ sudo sensors-detect ...
  • linux获取cpu温度控制风扇频率

    千次阅读 2020-03-16 09:47:31
    思路:底层驱动端创建线程不通过上层控制获取cpu温度模拟pwm控制风扇频率 主要函数: kthread_run();线程创建函数 filp_open();底层用于打开文件 get_fs();取得当前的地址访问限制值 set_fs();设置当前的地址...
  • linux cpu温度命令Most modern servers or computers have sensors to detect the temperature of various components. On Linux, how to get the CPU core temperatur in command linux? 大多数现代服务器或计算机...
  • Linux下查看CPU温度

    万次阅读 2018-01-11 09:10:11
    Linux下可以通过lm_sensors来查看CPU温度(当然你的硬件首先要支持),且使用这个功能要有内核相关模块(比如I2C)的支持 先查看机器上是否安装了lm_sensors: # rpm -q lm_sensors 如果没有安装直接yum安装:...
  • Linux系统cpu、内存等信息获取并放在同一个文件中的C++源码,需要g++才能编译
  • 本源码在CSDN IT1995的博客有代码详解,欢迎大家参考。谢谢!
  • linux获取CPU温度

    2014-06-08 12:29:00
    linux获取CPU温度 Centos系列 1 yum install lm_sensors 2 sensors-detect 3 sensors Ubuntu系列(多了service module-init-...
  • Linux如何查看CPU温度

    万次阅读 2015-06-11 18:12:14
    下面介绍Linux下查看CPU温度的方法. CentOS系列:  1.yum install lm_sensors; 2.sensors-detect 3.sensors Ubuntu系列: 1.apt-get install lm-sensors 2.sensors-detect 3.service kmod start 4.sensor
  • Linux查看机器CPU温度

    千次阅读 2017-09-09 15:06:48
    Linux查看机器CPU温度一、安装lm_sensors[root@MPI_EXERCISE ~]# yum -y install lm_sensors二、配置[root@MPI_EXERCISE ~]# sensors-detectDo you want to scan for them? This is totally safe. (YES/no): yesDo ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,988
精华内容 1,595
关键字:

linux下获取cpu温度

linux 订阅