拆分结果 Python 用于 CPU 用法

Split results in Python for CPU usage

几个小时以来一直在努力让它发挥作用。我没有尝试将此文本拆分。我只想要这个

中的当前 CPU
>>> from __future__ import print_function
>>> from urllib.request import urlopen
>>> import json
>>> import subprocess
>>> import requests
>>> import random
>>> import sys
>>> import os
>>> import time
>>> import datetime
>>> import MySQLdb as my
>>> import psutil
>>> os.popen('vcgencmd measure_temp').readline()
"temp=52.0'C\n"
>>> cpu = psutil.cpu_freq()
>>> cpu = cpu.split('current=')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'scpufreq' object has no attribute 'split'
>>> psutil.cpu_freq()
scpufreq(current=600.0, min=600.0, max=1500.0)
>>> psutil.cpu_freq(percpu=True)
[scpufreq(current=600.0, min=600.0, max=1500.0)]
>>> cpu = psutil.cpu_freq(percpu=True)
>>> cpu.split('=')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'split'
>>> AttributeError: 'list' object has no attribute 'split'
  File "<stdin>", line 1
    AttributeError: 'list' object has no attribute 'split'
                                ^
SyntaxError: invalid syntax
>>> AttributeError: 'list' object has no attribute 'split'
  File "<stdin>", line 1
    AttributeError: 'list' object has no attribute 'split'
                                ^
SyntaxError: invalid syntax
>>> psutil.cpu_freq(percpu=True).readline()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'readline'
>>> cpu = psutil.cpu_freq()

我哪里出错了?

OS:拉斯比克星 Python: python3 画中画:pip3

您似乎忽略了错误消息:

>>> cpu = psutil.cpu_freq()
>>> cpu = cpu.split('current=')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'scpufreq' object has no attribute 'split'

来自 psutil.cpu_freq() 的 return 值不是字符串,因此它没有 split 方法。如果你只是打印值...

>>> cpu
scpufreq(current=700.0, min=700.0, max=800.0)

...你知道它有什么属性,事实上,我们可以像这样访问这些值:

>>> cpu.current
700.0
>>> cpu.max
800.0

当您设置 percpu=True 时,您将返回一个列表:

>>> psutil.cpu_freq(percpu=True)
[scpufreq(current=600.0, min=600.0, max=1500.0)]

再一次,list 不是字符串,所以没有 split 方法。由于只有一个 CPU,您会得到一个包含 1 个项目的列表,因此您可以像这样访问值:

>>> cpu = psutil.cpu_freq(percpu=True)
>>> cpu[0].current
700.0