Python psutil.net_connections()应该返回namedtuple,但它的行为不是一个

Python psutil.net_connections()应该返回namedtuple,但它的行为不是一个,python,filter,psutil,Python,Filter,Psutil,我正在尝试确定我的服务器(应该在127.0.0.1:5000上运行)是否正在实际运行。我正在尝试使用psutil.net\u connections()来解决这个问题: filter(lambda conn: conn.raddr.ip == '127.0.0.1' and conn.raddr.port == 5000, psutil.net_connections()) 这应该给我与我的服务器对应的项目,为了检查我是否真的得到了什么,我只需检查len(tuple(…)。但是,使用tuple

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

filter(lambda conn: conn.raddr.ip == '127.0.0.1' and conn.raddr.port == 5000, psutil.net_connections())
这应该给我与我的服务器对应的项目,为了检查我是否真的得到了什么,我只需检查
len(tuple(…)
。但是,使用
tuple(…)
会给我
AttributeError:“tuple”对象没有我没有得到的属性“ip”
,因为内部tuple(即
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

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

raddr
:远程地址作为
(ip,端口)
命名元组或UNIX套接字的绝对路径。当远程端点未连接时,您将得到一个空元组
(AF\u INET*)
“”
(AF\u UNIX)。有关UNIX套接字,请参见下面的注释

因此,在尝试访问
ip
port
属性之前,应检查
raddr
是否为空

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