python cpu温度

by Ori Roza

通过Ori Roza

使用Python(和其他一些不错的技巧)检查CPU的温度 (Check the temperature of your CPU using Python (and other cool tricks))

Python’s psutil module provides an interface with all the PC resources and processes.

Python的psutil模块提供了与所有PC资源和进程的接口。

This module is very helpful whether we want to get some data on a specific resource or manage a resource according to its state.

无论我们要获取特定资源上的某些数据还是根据其状态管理资源,此模块都非常有用。

In this article, I will show you the main features of this module and how to use them.

在本文中,我将向您展示该模块的主要功能以及如何使用它们。

获取PC资源信息 (Getting PC resources information)

Let’s see how we can get some info about our PC’s current system state.

让我们看看如何获​​取有关PC当前系统状态的信息。

We can get some info about the CPU since boot time, including how many system calls and context switches it has made:

自启动以来,我们可以获得有关CPU的一些信息,包括它进行了多少次系统调用和上下文切换 :

In [1]: psutil.cpu_stats()Out[1]: scpustats(ctx_switches=437905181,interrupts=2222556355L,soft_interrupts=0,syscalls=109468308)

We can get some info about the disk and the memory state:

我们可以获得有关磁盘和内存状态的一些信息:

In [1]: psutil.disk_usage("c:")Out[1]: sdiskusage(total=127950385152L,                   used=116934914048L,                   free=11015471104L,                   percent=91.4)
In [2]: psutil.virtual_memory()Out[2]: svmem(total=8488030208L,              available=3647520768L,              percent=57.0,              used=4840509440L,              free=3647520768L)

We can even get some physical information about how many seconds of battery life is left, or the current CPU temperature:

我们甚至可以获得有关剩余电池寿命或当前CPU温度的一些物理信息:

In [1]: psutil.sensors_battery()Out[1]: sbattery(percent=77, secsleft=18305, power_plugged=False)
In [2]: psutil.sensors_temperatures() # In CelsiusOut[2]: {'ACPI\\ThermalZone\\THM0_0':         [shwtemp(label='',          current=49.05000000000001,          high=127.05000000000001,          critical=127.05000000000001)]}

获取有关流程的信息 (Getting Information about Processes)

One of the most powerful features this module provides us is the “Process” class. We can access each process’ resources and statistics and respond accordingly.

该模块为我们提供的最强大的功能之一是“ Process”类。 我们可以访问每个流程的资源和统计信息,并做出相应的响应。

(There are processes that require some admin or system privileges, so after trying to access their instance it will fail with an “AccessDenied” error.)

(有些进程需要某些管理员或系统特权,因此在尝试访问其实例后,它将失败,并显示“ AccessDenied”错误。)

Let’s check this feature out.

让我们检查一下此功能。

First, we create an instance by giving the wanted process ID:

首先,我们通过提供所需的进程ID创建一个实例:

In [1]: p = psutil.Process(9800)

Then, we can access all the information and statistics of the process:

然后,我们可以访问该过程的所有信息和统计信息:

In [1]: p.exe()Out[1]: 'C:\\Windows\\System32\\dllhost.exe'
In [2]: p.cpu_percent()Out[2]: 0.0
In [3]: p.cwd()Out[3]: 'C:\\WINDOWS\\system32'

Let’s create a function that links open connections ports to processes.

让我们创建一个将打开的连接端口链接到进程的函数。

First, we need to iterate all the open connections. ps.net_connections is exactly what we need!

首先,我们需要迭代所有打开的连接。 ps.net_connections正是我们需要的!

In [1]: ps.net_connections?Signature: ps.net_connections(kind='inet')Docstring:Return system-wide socket connections as a list of(fd, family, type, laddr, raddr, status, pid) namedtuples.In case of limited privileges 'fd' and 'pid' may be set to -1and None respectively.The *kind* parameter filters for connections that fit thefollowing criteria:
+------------+----------------------------------------------------+| Kind Value | Connections using                                  |+------------+----------------------------------------------------+| inet       | IPv4 and IPv6                                      || inet4      | IPv4                                               || inet6      | IPv6                                               || tcp        | TCP                                                || tcp4       | TCP over IPv4                                      || tcp6       | TCP over IPv6                                      || udp        | UDP                                                || udp4       | UDP over IPv4                                      || udp6       | UDP over IPv6                                      || unix       | UNIX socket (both UDP and TCP protocols)           || all        | the sum of all the possible families and protocols |+------------+----------------------------------------------------+

We can see that one of the attributes that net_connections returns is “pid”.

我们可以看到net_connections返回的属性之一是“ pid”。

We can link this to a process name:

我们可以将其链接到进程名称:

In [1]: def link_connection_to_process():    ...:     for connection in ps.net_connections():    ...:         try:    ...:             yield [ps.Process(pid=connection.pid).name(),    ...:                   connection]    ...:         except ps.AccessDenied:    ...:             continue # Keep going if we don't have access

We should remember that unless we’ve got some root privileges, we cannot access particular processes. Therefore we need to wrap it in a try-catch statement for handling an “AccessDenied” error.

我们应该记住,除非拥有某些root特权,否则我们将无法访问特定进程。 因此,我们需要将其包装在try-catch语句中,以处理“ AccessDenied”错误。

Let’s check the output.

让我们检查输出。

It will output a lot of data, so let’s print the first member:

它将输出大量数据,因此让我们打印第一个成员:

In [1]: for proc_to_con in ps.net_connections():    ...:     print proc_to_con    ...:     raw_input("...")    ...:['ManagementServer.exe', sconn(fd=-1, family=2, type=1, laddr=addr(ip='127.0.0.1', port=5905), raddr=addr(ip='127.0.0.1', port=49728), status='ESTABLISHED', pid=5224)]...

As we can see, the first member is the process name and the second is the connection data: ip address, port, status and so on.

如我们所见,第一个成员是进程名称,第二个是连接数据:ip地址,端口,状态等。

This function is very useful to explore which ports are used by each processes.

此功能对于探索每个进程使用哪些端口非常有用。

We’ve all gotten the error “This address is already in use” once, haven’t we?

我们一次都收到错误消息“此地址已被使用”,不是吗?

结论 (Conclusion)

The psutil module is a great library for system management. It is useful for managing resources as a part of a code flow.

psutil模块是用于系统管理的出色库。 对于将资源作为代码流的一部分进行管理很有用。

I hope this article taught you something new, and I am looking forward to your feedback. Please, do tell — was this useful for you?

希望本文能教给您一些新的知识,并期待您的反馈。 请告诉-这对您有用吗?

翻译自: https://www.freecodecamp.org/news/using-psutil-in-python-8623d9fac8dd/

python cpu温度

python cpu温度_使用Python(和其他一些不错的技巧)检查CPU的温度相关推荐

  1. python 时间序列预测_使用Python进行动手时间序列预测

    python 时间序列预测 Time series analysis is the endeavor of extracting meaningful summary and statistical ...

  2. python 概率分布模型_使用python的概率模型进行公司估值

    python 概率分布模型 Note from Towards Data Science's editors: While we allow independent authors to publis ...

  3. python集群_使用Python集群文档

    python集群 Natural Language Processing has made huge advancements in the last years. Currently, variou ...

  4. python 网页编程_通过Python编程检索网页

    python 网页编程 The internet and the World Wide Web (WWW), is probably the most prominent source of info ...

  5. python机器学习预测_使用Python和机器学习预测未来的股市趋势

    python机器学习预测 Note from Towards Data Science's editors: While we allow independent authors to publish ...

  6. python 多核并行计算_嫌Python太慢?并行运算Process Pools三行代码给你4倍提速!

    大数据文摘作品,转载要求见文末,作者 | Adam Geitgey,编译 | 元元.Lisa.Saint.Aileen. Python绝对是处理数据或者把重复任务自动化的绝佳编程语言.要抓取网页日志? ...

  7. python计算信息增益_利用Python提取ABAQUS的计算结果(ODB)信息、体积、应变等变化(一)...

    00 实例模型 一个金属长方体,我们需要对其做拉伸的加载约束示意图如图1,并在完成后采用Python命令流读取参考点的位移.体积.应变随加载时间的变化情况. 图1 金属长方体约束加载示意图 01 Py ...

  8. python高斯求和_利用Python进行数据分析(3)- 列表、元组、字典、集合

    本文主要是对Python的数据结构进行了一个总结,常见的数据结构包含:列表list.元组tuple.字典dict和集合set. image 索引 左边0开始,右边-1开始 通过index()函数查看索 ...

  9. python移动图形工作站_让Python跑得更快

    原标题:让Python跑得更快 点击关注 异步图书,置顶公众号 每天与你分享 IT好书 技术干货 职场知识 Tips 参与文末话题讨论,即有机会获得异步图书一本. Python很容易学.你之所以阅读本 ...

最新文章

  1. 用Hadoop进行分布式并行编程
  2. OpenDDS安装与开发
  3. Linux scp 免密码 传输文件
  4. ajax的模式_AJAX的完整形式是什么?
  5. Emscripten 单词_极光单词独创多种学习方法助您高效背单词
  6. java socket 远程调用_使用Socket反射Java流操作进行方法的远程调用(模拟RPC远程调用)...
  7. dos打开计算机管理,小何 发布 DOS 命令打开控制面板各项东东 你们懂得...
  8. matlab将列数据存成excel表格,matlab将列数据存成excel表格-matlab工作区数据怎么转为excel...
  9. 查看虚拟机cpu型号_KVM虚拟机,如何设置虚拟机的CPU型号与物理机是一样的
  10. linux mint 忘记密码,在Linux Mint中如何提醒mysql localhost base的密码?
  11. oracle级联更新与级联删除
  12. 2008服务器操作系统安装,Windows server2008服务器安装图文教程
  13. 加密货币大崩盘:第一季度最大跌幅高达 88%!
  14. 从一个git仓库拷贝到另一个git仓库
  15. 嵌入式系——软件管理工程
  16. 关于HTTP缓存的故事
  17. Himawari-8 数据介绍及下载方法
  18. CAP理论维基百科翻译
  19. CSS3选择器(全部)
  20. 商业智能如何助推电商

热门文章

  1. larval 数据库迁移
  2. 触发器实例精讲-志在必得
  3. 项目目标的SMART原则
  4. adb查看手机设备型号、品牌、机型等信息
  5. 任意阶幻方的解法及c++实现
  6. 启动Nginx时报错:error while loading shared libraries: librdkafka.so.1: cannot open shared object file: No
  7. 从0到1000万:哔哩哔哩直播架构演进史
  8. linux泰语语言包,linux安装中文语言包(示例代码)
  9. LED点阵显示,有关特殊国别(阿拉伯,希伯来,泰文)字符排版和乱码问题解决
  10. 我的世界正版服务器客户端,我的世界1.11.2