psutil.net_connections() 应该 return namedtuple,但它不是一个
psutil.net_connections() should return namedtuple, but it is not behaving as one
我正在尝试查明我的服务器(在 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
并非所有 raddr
都有 ip
属性。文档说:
raddr
: the remote address as a (ip, port)
named tuple or an absolute path in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple (AF_INET*)
or ""
(AF_UNIX). For UNIX sockets see notes below.
因此,在尝试访问 ip
和 port
属性之前,您应该检查 raddr
是否不为空。
filter(lambda conn: conn.raddr and conn.raddr.ip == '127.0.0.1' and conn.raddr.port == 5000, psutil.net_connections())
我正在尝试查明我的服务器(在 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
并非所有 raddr
都有 ip
属性。文档说:
raddr
: the remote address as a(ip, port)
named tuple or an absolute path in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple(AF_INET*)
or""
(AF_UNIX). For UNIX sockets see notes below.
因此,在尝试访问 ip
和 port
属性之前,您应该检查 raddr
是否不为空。
filter(lambda conn: conn.raddr and conn.raddr.ip == '127.0.0.1' and conn.raddr.port == 5000, psutil.net_connections())