Invictus
Invictus

Reputation: 2780

python regular expression error

I am trying do a pattern search and if match then set a bitarray on the counter value.

runOutput = device[router].execute (cmd)
            runOutput = output.split('\n')
            print(runOutput)
            for this_line,counter in enumerate(runOutput):
                print(counter)
                if  re.search(r'dev_router', this_line) :
                    #want to use the counter to set something

Getting the following error:

if re.search(r'dev_router', this_line) :

2016-07-15T16:27:13: %ERROR: File "/auto/pysw/cel55/python/3.4.1/lib/python3.4/re.py", line 166,

in search 2016-07-15T16:27:13: %-ERROR: return _compile(pattern, flags).search(string)

2016-07-15T16:27:13: %-ERROR: TypeError: expected string or buffer

Upvotes: 0

Views: 947

Answers (1)

alecxe
alecxe

Reputation: 473813

You mixed up the arguments for enumerate() - first goes the index, then the item itself. Replace:

for this_line,counter in enumerate(runOutput):

with:

for counter, this_line in enumerate(runOutput):

You are getting a TypeError in this case because this_line is an integer and re.search() expects a string as a second argument. To demonstrate:

>>> import re
>>>
>>> this_line = 0
>>> re.search(r'dev_router', this_line)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/user/.virtualenvs/so/lib/python2.7/re.py", line 146, in search
    return _compile(pattern, flags).search(string)
TypeError: expected string or buffer

By the way, modern IDEs like PyCharm can detect this kind of problems statically:

enter image description here

(Python 3.5 is used for this screenshot)

Upvotes: 2

Related Questions