如何在python下读取ip地址而不泄漏资源

如何在python下读取ip地址而不泄漏资源,python,ip,resource-leak,Python,Ip,Resource Leak,如何在Linux和Windows中用Python获取网络信息?我尝试在Ubuntu 12.10 64位上使用Python2.7中的netinfo软件包ver 0.3.2,但使用该软件包会使句柄不关闭,如下所示。就我而言,这是不可接受的 import netinfo def countOpenFiles(): import resource, fcntl, os n_open = 0 names = [] soft, hard = resource.getrlim

如何在Linux和Windows中用Python获取网络信息?我尝试在Ubuntu 12.10 64位上使用Python2.7中的netinfo软件包ver 0.3.2,但使用该软件包会使句柄不关闭,如下所示。就我而言,这是不可接受的

import netinfo def countOpenFiles(): import resource, fcntl, os n_open = 0 names = [] soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) for fd in range(0, soft): try: f = fcntl.fcntl(fd, fcntl.F_GETFD) n_open += 1 except IOError: continue return n_open for i in range(10): netinfo.get_ip('eth0') print countOpenFiles() 它产生:

4 5 6 7 8 9 10 11 12 13 我想有类似的netinfo包没有资源泄漏


谢谢你的帮助。

你到底想做什么? 在我看来,您不计算eth0文件句柄,而是计算所有文件句柄。 如果您只是不想打开IP文件句柄,那么可以在Linux下使用lsof shelltool

lsof-u您的用户| grep IPv4
不只是eth0,但我不知道如何为接口过滤它。

我想读取wlan0接口的ip地址。此过程是连续的,例如,应每秒进行一次查询。netinfo.get_ip方法不会释放资源处理程序,如示例所示。在python中1024个处理程序的时间限制之后,python进程将带着错误退出。感谢您的回答。我发现这个库运行良好,不会泄漏。