python - 为什么正则表达式函数总是弹出属性错误?

标签 python regex attributeerror

我一直在用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/

相关文章:

regex - 使用 regex_replace 删除 ansible playbook 中的字符

python-3.x - Lenstras 椭圆曲线属性错误问题

python - 光标: AttributeError: 'NoneType' object has no attribute 'fetchall'

python - AttributeError:模块 'keras.api._v2.keras.utils' 没有属性 'Sequential' 我刚刚启动神经网络,因此需要帮助

c# - 如何匹配正确的组名(.NET C# Regex)

java - 使用字符串数组时如何编写 lambda 表达式?

python - 在 Python 中使用 Webbrowser 模块打开选项卡

python - 为什么重新计算 ORB 描述符比从磁盘加载它更快?

python - 所有中间步骤都应该是变压器并实现拟合和变换

python - 从 Android 客户端调用在 Azure VM 中运行的 python 函数