使用Python3获取系统信息

获取CPU温度

读取/sys/class/thermal/thermal_zone0/temp文件中的内容,除以1000后,即可获得CPU的温度,单位为摄氏度。

适用环境:

  • Linux
  • Android + QPython3

代码示例:

fp = open('/sys/class/thermal/thermal_zone0/temp', 'r');
result_c = fp.readline();
fp.close();
cpu_temp = int(float(result_c) / 1000.0); #获取CPU温度

获取Nvidia GPU温度

运行nvidia-smi --query-gpu=temperature.gpu --format=csv,noheader,nounits命令,该命令的标准输出即为GPU的温度,单位为摄氏度。

适用环境:

  • Windows(需要安装Nvidia官方驱动)
  • Linux(需要安装Nvidia官方驱动)

代码示例:

import subprocess;
p = subprocess.Popen(['nvidia-smi', '--query-gpu=temperature.gpu', '--format=csv,noheader,nounits'], stdout=subprocess.PIPE);
gpu_temp = int(p.communicate()[0]);  #获取GPU温度

获取Android手机电池电量

使用SL4A的BatteryManagerFacade API获取手机电池电量。

适用环境:

  • Android + QPython3

代码示例:

import android;
droid = android.Android();
droid.batteryStartMonitoring();
battery_level = droid.batteryGetLevel()[1]; #获取Android手机电池电量
droid.batteryStopMonitoring();

获取总CPU使用率

通过分析/proc/stat文件中的内容获取CPU使用率。

适用环境:

  • Linux
  • Android + QPython3

代码示例:

import time;
def cpu_usage(sample_interval):
    with open('/proc/stat', 'r') as fp:
        info0 = fp.readline();
    time.sleep(sample_interval);
    with open('/proc/stat', 'r') as fp:
        info1 = fp.readline();
    info0 = [int(n) for n in info0.split()[1:]];
    info1 = [int(n) for n in info1.split()[1:]];
    return float(sum(info1[0:3]) - sum(info0[0:3])) / float(sum(info1) - sum(info0));

# 调用cpu_usage()函数
print(cpu_usage(0.01));

获取每个CPU的使用率

通过分析/proc/stat文件中的内容获取CPU数量,以及每个CPU的使用率。

适用环境:

  • Linux
  • Android + QPython3

代码示例:

import time, re;
__re_cpu = re.compile(r'cpu\d+');
def cpu_usage_each(sample_interval):
    with open('/proc/stat', 'r') as fp:
        lines0 = fp.readlines();
    time.sleep(sample_interval);
    with open('/proc/stat', 'r') as fp:
        lines1 = fp.readlines();
    lines0 = [l.split() for l in lines0];
    lines1 = [l.split() for l in lines1];
    info0, info1, result = [], [], [];
    for l in lines0:
        if None != __re_cpu.match(l[0]):
            info0.append([int(n) for n in l[1:]]);
    for l in lines1:
        if None != __re_cpu.match(l[0]):
            info1.append([int(n) for n in l[1:]]);
    for i in range(len(info0)):
        total = sum(info1[i]) - sum(info0[i]);
        if 0 == total:
            result.append(0.0);
        else:
            result.append(float(sum(info1[i][0:3]) - sum(info0[i][0:3])) / float(total));
    return result;

# 调用cpu_usage_each()函数
print(cpu_usage_each(0.01));

获取内存使用率

通过分析/proc/meminfo文件中的内容获取内存使用率。

适用环境:

  • Linux
  • Android + QPython3

代码示例:

import re;
__re_mem_total = re.compile(r'MemTotal:\s*(\d+)');
__re_mem_free = re.compile(r'MemFree:\s*(\d+)');
__re_mem_buffers = re.compile(r'Buffers:\s*(\d+)');
__re_mem_cache = re.compile(r'Cached:\s*(\d+)');
def mem_usage():
    with open('/proc/meminfo', 'r') as fp:
        meminfo = fp.readlines();
    total, avail = 1, 0;
    for line in meminfo:
        m_total = __re_mem_total.match(line);
        m_free = __re_mem_free.match(line);
        m_buffers = __re_mem_buffers.match(line);
        m_cache = __re_mem_cache.match(line);
        if None != m_total:
            total = int(m_total.groups()[0]);
        elif None != m_free:
            avail += int(m_free.groups()[0]);
        elif None != m_buffers:
            avail += int(m_buffers.groups()[0]);
        elif None != m_cache:
            avail += int(m_cache.groups()[0]);
    return float(total-avail)/float(total);

# 调用mem_usage()函数
print(mem_usage());

获取开机时间

通过分析/proc/uptime文件中的内容获取从开机到现在的秒数。

适用环境:

  • Linux
  • Android + QPython3

代码示例:

from datetime import datetime, timedelta;
def boot_time():
    with open('/proc/uptime', 'r') as fp:
        uptime = fp.readline();
    uptime = float(uptime.split()[0]);
    return (datetime.now() - timedelta(0, uptime));

# 调用boot_time()函数
print(boot_time().strftime('%Y-%m-%dT%H:%M:%S'));

使用psutil获取CPU使用率、内存使用率、开机时间

使用psutil提供的API获取CPU使用率(单位为百分比)、内存使用率(单位为百分比)、开机时间。

需要另外安装psutil模块。

适用环境:

  • Windows
  • Linux

代码示例(获取CPU使用率):

import psutil;
from datetime import datetime;

#获取总CPU使用率
cpu_usage = psutil.cpu_percent(0.1);

#获取内存使用率
meminfo = psutil.virtual_memory();
mem_usage = (meminfo.total - meminfo.available) / meminfo.total * 100;

#获取开机时间
boot_time = datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%dT%H:%M:%S');
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值