Invictus Invictus - 1 year ago 80
Python Question

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')
for this_line,counter in enumerate(runOutput):
if'dev_router', this_line) :
#want to use the counter to set something

Getting the following error:

if'dev_router', this_line) :

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

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

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

Answer Source

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

for this_line,counter in enumerate(runOutput):


for counter, this_line in enumerate(runOutput):

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

>>> import re
>>> this_line = 0
>>>'dev_router', this_line)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/user/.virtualenvs/so/lib/python2.7/", 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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download