繁体   English   中英

如何在没有 psutil 的情况下获取 CPU 和 RAM 使用率

[英]How to get CPU and RAM usage without psutil

出于安全原因,我不允许使用从 pypi 下载的任何包,包括 PSUTIL。 有没有办法可以在没有它的情况下检索 CPU 使用率和 RAM 使用率?

我相信已经存在一个问题,我可以读取/proc/stat的解决方案,但这不是我的选择,因为我使用的是 Windows 服务器,而不是 linux。

我在想也许我可以执行“获取 CPU/RAM 使用情况”shell 命令并在 Python 中打印 output 使用子进程模块,但我得到一个错误。 这是我的代码:

import subprocess
result = subprocess.run(['Get-WmiObject -Class Win32_Processor | Select LoadPercentage', '-l'], stdout=subprocess.PIPE)

result.stdout

我收到“FileNotFoundError:[WinError 2] 系统找不到指定的文件”错误。

更详细的错误信息:

  File "C:\Users\acer\Documents\Test.py", line 2, in <module>
    result = subprocess.run(['Get-WmiObject -Class Win32_Processor | Select LoadPercentage', '-l'], stdout=subprocess.PIPE)
  File "C:\Users\acer\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 501, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\acer\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 969, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\acer\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1438, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

subprocess.run在 windows 命令提示符下运行您的命令。 要在 powershell 中运行它,您需要首先在命令提示符下调用 powershell。 您只需在 arguments 列表前添加"powershell"即可完成此操作

result = subprocess.run(['powershell', 'Get-WmiObject -Class Win32_Processor | Select LoadPercentage'], stdout=subprocess.PIPE)

print(result.stdout)

印刷

b'\r\nLoadPercentage\r\n--------------\r\n             5\r\n\r\n\r\n'

由于此 output 是bytes类型,因此您必须对其进行解码并从中解析出数字。 split结果并选择了最后一个元素,但您可以使用您喜欢的任何其他方法:

result_s = result.stdout.decode("ascii")
cpu_load = int(result_s.split()[-1])        # gives cpu_load = 5

请注意,我删除了您'-l'参数,因为这会导致我的计算机出现错误。 我不熟悉Select命令(或任何 powershell,真的)告诉你如何解决它,但无论如何它似乎与问题无关。

Select-Object : Missing an argument for parameter 'Last'. Specify a parameter of type 'System.Int32' and try again.
At line:1 char:62
+ Get-WmiObject -Class Win32_Processor | Select LoadPercentage -l
+                                                              ~~
    + CategoryInfo          : InvalidArgument: (:) [Select-Object], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.SelectObjectCommand

暂无
暂无

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

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