2

python file

import ConfigParser,re

config=ConfigParser.ConfigParser()
with open("temp.cfg",'r') as config_file:
    config.readfp(config_file)


x=[]
x.append(re.compile(r'abc'))
x.append((config.get("ssp",'a')).strip('"'))
print x[0]
print x[1]

config file[temp.cfg]

[ssp]
a:re.compile(r'abc')

output

>>> 
<_sre.SRE_Pattern object at 0x02110F80>
re.compile(r'abc')
>>>

What "print x[1]" should give is regular expression object but it seems to be returning string.

Looks like I am not doing it in the right way & am unable to figure it out

Ravi Yadav
  • 405
  • 4
  • 16

2 Answers2

2

The output of x[1] is because of the following:

x.append((config.get("ssp",'a')).strip('"'))

Since, config is the cfg file parser object, you are accessing the option a of ssp section:

[ssp]
a:re.compile(r'')

which is obviously, the string: re.compile(r'').

Using eval:

x.append(eval((config.get("ssp",'a')).strip('"')))
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
0

You need to change your config file to this:

[ssp]
a:abc

Then you can simply do (without ugly eval())

x.append(re.compile(config.get("ssp", "a")).strip())

You read the regex string first from config file and then translate it to a regex object in your code with re.compile() instead of eval(). That's also better for maintainance, because you save a lot of text in the config file (a:abc instead of a:re.compile(r'abc') for each line).

Community
  • 1
  • 1
colidyre
  • 4,170
  • 12
  • 37
  • 53
  • It's better not using `eval()` imho. Especially if you can avoid it. See [this](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) to get only an impression about using `eval()` Does my example work for you? – colidyre Oct 20 '15 at 12:14
  • x.append(re.compile(config.get("ssp", "a")).strip()) give different address for e.g >>> <_sre.SRE_Pattern object at 0x02310F80> <_sre.SRE_Pattern object at 0x0223AC50> – Ravi Yadav Oct 20 '15 at 12:34
  • That's only the address in the memory where the pattern is saved. Normally, it isn't really interesting. I don't get the relevance for it. Do you need to proof if regexes reference to same object in memory or change regex outside of Python (the latter one is not a good idea at all, for the first one you need at least two same string regexes)? – colidyre Oct 20 '15 at 12:44
  • More information: The output for the compiled regex (which you cannot have in a human-friendly way) is a `__repr__()`, i.e. a helpful information which have a little object information and the memory address (I'm not sure, but I think `id()` was taken internally). So this information is only relevant if you want to ensure/test object identity like _object A_ __is__ _object B_: _True_ / _False_. – colidyre Oct 20 '15 at 12:58
  • it wasn't working & I have other things to do so i am using eval for the time being – Ravi Yadav Oct 28 '15 at 05:22