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

2024-09-27 09:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出我的服务器(应该在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


Tags: and项目lambdainip服务器netport
1条回答
网友
1楼 · 发布于 2024-09-27 09:29:28

并非所有的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.

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

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

相关问题 更多 >

    热门问题