【问题标题】:Split results in Python for CPU usage在 Python 中拆分结果以获取 CPU 使用率
【发布时间】:2020-01-05 00:40:52
【问题描述】:

现在已经尝试让它工作了几个小时。我没有尝试将这段文字分开。我只想要当前的 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()

我哪里错了?

操作系统:Rasbian Buster 蟒蛇:python3 画中画:pip3

【问题讨论】:

    标签: python-3.x linux pip raspberry-pi3


    【解决方案1】:

    看起来您似乎忽略了错误消息:

    >>> 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() 的返回值不是字符串,因此它没有 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
    

    【讨论】:

    • 还有一个问题。我怎样才能以同样的方式转换它?文件系统 1K-blocks Used 可用 Use% Mounted on /dev/sda2 4883638268 2688204740 2195433528 56% /media/external
    • 这可能值得第二个问题。如果您将其保存在字符串中,您想要使用split 方法。
    猜你喜欢
    • 2022-01-26
    • 2020-11-27
    • 2012-10-19
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    相关资源
    最近更新 更多