首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python TypeError:“_sre.SRE_Match”对象没有属性“”__getitem__“”

Python TypeError:“_sre.SRE_Match”对象没有属性“”__getitem__“”
EN

Stack Overflow用户
提问于 2018-10-17 14:07:18
回答 1查看 1.6K关注 0票数 2

我是一个全新的python和编码新手,我正在努力学习下面的工作。这是测试代码,如果我能让它工作,我应该能够在它上面构建。

就像我说的,我是个新手,如果这是个愚蠢的错误,我很抱歉。

代码语言:javascript
复制
# coding=utf-8
import ops         # Import the OPS module.
import sys         # Import the sys module.
import re

# Subscription processing function
def ops_condition (o): 
    enter code herestatus, err_str = o.timer.relative("tag",10)
    return status

def ops_execute (o):
    handle, err_desp = o.cli.open()
    print("OPS opens the process of command:",err_desp)
    result, n11, n21 = o.cli.execute(handle,"return")
    result, n11, n21 = o.cli.execute(handle,"display interface brief | include Ethernet0/0/1")  
    match = re.search(r"Ethernet0/0/1\s*(\S+)\s*", result)

    if not match:
        print("Could not determine the state.")
        return 0  

    physical_state = match[1]  # Gets the first group from the match.
    print (physical_state)
    if physical_state == "down":
            print("down")
            result = o.cli.close(handle)
    else :
        print("up")
        return 0

错误

代码语言:javascript
复制
<setup>('OPS opens the process of command:', 'success')

Oct 17 2018 11:53:39+00:00 setup %%01OPSA/3/OPS_RESULT_EXCEPTION(l)[4]:Script is                            test.py, current event is tag, instance is 1515334652, exception reason is Trac                           eback (most recent call last):
  File ".lib/frame.py", line 114, in <module>
    ret = m.ops_execute(o)
  File "flash:$_user/test.py", line 22, in ops_execute
    physical_state = match[1]  # Gets the first group from the match.
TypeError: '_sre.SRE_Match' object has no attribute '__getitem__'
EN

回答 1

Stack Overflow用户

发布于 2018-10-17 14:09:01

正则表达式匹配对象的__getitem__方法是从Python3.6开始添加的。如果您使用的是早期版本,则可以改用group方法。

更改:

代码语言:javascript
复制
physical_state = match[1]

至:

代码语言:javascript
复制
physical_state = match.group(1)

请参考documentation了解详细信息。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52848239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档