【问题标题】:psutil.net_connections() should return namedtuple, but it is not behaving as onepsutil.net_connections() 应该返回 namedtuple,但它的行为不是一个
【发布时间】:2020-12-23 01:37:39
【问题描述】:

我正在尝试确定我的服务器(应该在127.0.0.1:5000 上运行)是否真的在运行。我正在尝试使用psutil.net_connections() 来解决这个问题:

filter(lambda conn: conn.raddr.ip == '127.0.0.1' and conn.raddr.port == 5000, psutil.net_connections())

这应该给我该项目对应于我的服务器,并检查我是否真的得到了一些东西,我只需检查len(tuple(...)))。然而,使用tuple(...) 给了我AttributeError: 'tuple' object has no attribute 'ip',这是我没有得到的,因为内部元组(即conn.raddr 确实有一个“ip”属性)。

定期循环时也会发生这种情况:

In [22]: for conn in psutil.net_connections():
    ...:     if conn.raddr.ip == '127.0.0.1' and conn.raddr.port == 5000:
    ...:         break
    ...: else:
    ...:     print('server is down')

但是当这样使用它时,它可以工作!

In [23]: a=psutil.net_connections()[0]
In [24]: a.raddr.ip
Out[24]: '35.190.242.205'

psutil 版本:5.7.2

【问题讨论】:

    标签: python filter psutil


    【解决方案1】:

    并非所有raddr 都具有ip 属性。文档说:

    raddr:远程地址为 (ip, port) 命名元组或 UNIX 套接字的绝对路径。当远程端点未连接时,您将获得一个空元组 (AF_INET*)"" (AF_UNIX)。对于 UNIX 套接字,请参见下面的注释。

    因此,在尝试访问 ipport 属性之前,您应该检查 raddr 是否为空。

    filter(lambda conn: conn.raddr and conn.raddr.ip == '127.0.0.1' and conn.raddr.port == 5000, psutil.net_connections())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2019-04-10
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多