如果从 config.cfg 文件中获取,则正则表达式模式对象将转换为字符串

regular expression Pattern object getting converted to string if fetched from config.cfg file

python 文件

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]

配置文件[temp.cfg]

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

输出

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

"print x[1]"应该给出的是正则表达式对象,但它似乎返回的是字符串。

看来我没有按正确的方式做,我无法弄清楚

x[1]的输出是因为:

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

由于 config 是 cfg 文件解析器对象,您正在访问 ssp 部分的选项 a

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

很明显,字符串re.compile(r'').

使用eval:

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

您需要将配置文件更改为:

[ssp]
a:abc

那你就可以简单地做(不丑eval()

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

您从配置文件中首先读取正则表达式字符串,然后然后使用re.compile()将其转换为代码中的正则表达式对象] 而不是 eval()。这也有利于维护,因为您在配置文件中保存了大量文本(每行 a:abc 而不是 a:re.compile(r'abc'))。