我一直在用python编写一个函数来获取计算机的IP。代码如下:
def getip(self):
self.path = "/root"
self.iplist = []
os.chdir(self.path)
os.system("ifconfig > ipfinder")
try:
file = open("ipfinder","r")
self.pattern = '(\d{1,3}\.){3}\d{1,3}'
while True:
line = file.readline()
try:
ip = re.search(self.pattern, line).group()
self.iplist.append(ip)
except AttributeError:
pass
file.close()
except EOFError:
for ip in self.iplist:
print ip
我知道这不是获取机器 IP 的好方法。问题是每次都会弹出 AttributeError。为什么会发生这种情况?为什么找不到匹配项?
最佳答案
我在本地运行了它。发现有4处需要修改!
a) 正则表达式:-\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}
b) 读取时修剪任何额外的空间:- file.readline().strip()
c) 如果到达行尾,则中断 while:-
if line == '':
break
d) 不做re.search,而是做re.finall
在我的系统中运行且没有 AttributeError 的修改后的代码是:-
def getip(self):
self.path = "/root"
self.iplist = []
os.chdir(self.path)
os.system("ifconfig > ipfinder")
try:
file = open("ipfinder","r")
self.pattern = '\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}'
while True:
line = file.readline().strip()
if line == '':
break
try:
ip = re.findall(self.pattern, line)
self.iplist.append(ip)
except AttributeError:
pass
file.close()
except EOFError:
for ip in self.iplist:
print ip
关于python - 为什么正则表达式函数总是弹出属性错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38073396/