使用ConfigParser的新行?

2024-06-02 06:00:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用configParser的配置文件:

<br>
[ section one ]<br>
one = Y,Z,X <br><br>
[EG 2]<br>
ias = X,Y,Z<br>

我的程序可以很好地读取和处理这些值。

然而,其中一些部分将相当大。我需要一个配置文件,允许值在一个新行上,如下所示:

[EG SECTION]<br>
EG=<br>
item 1 <br>
item 2 <br>
item 3<br>
etc...

在我的代码中,我有一个简单的函数,它使用string.split()对值使用分隔符(或分隔符),显然现在设置为逗号。我尝试过\n的转义字符串,但它不起作用。

有人知道python的配置解析器是否可以做到这一点吗?
http://docs.python.org/library/configparser.html

# We need to extract data from the config 
def getFromConfig(currentTeam, section, value, delimeter):
    cp = ConfigParser.ConfigParser()
    fileName = getFileName(currentTeam)
    cp.read(fileName)
    try:
        returnedString = cp.get(section, value)
    except: # The config file could be corrupted
        print( "Error reading " + fileName + " configuration file." )
        sys.exit(1) #Stop us from crashing later
    if delimeter != "": # We may not need to split
        returnedList = returnedString.split(delimeter)
    return returnedList

我会用这个:

taskStrings = list(getFromConfig(teamName, "Y","Z",","))

Tags: tofrombr配置文件sectionneedfilenameitem
2条回答

这似乎是可能的。例如,在我自己的配置文件中,我有一个带有元组的列表对象:

[root]
path: /
redirectlist: [ ( r'^magic', '/file' ),
    ( r'^avplay', '/file' ),
    ( r'^IPTV', '/file' ),
    ( r'^box', '/file' ),
    ( r'^QAM', '/qam' ),
    ( r'.*opentv.*', '/qam' ),
    ( r'.+', '/file' ) ]

我确实:

redirectstr = _configdict.get('root', 'redirectlist')
redirects = eval(redirectstr)

请注意,我实际上正在评估这条线路,如果在野外使用,可能会导致安全漏洞。

ConfigParser_read()方法的docstring表示:

Continuations are represented by an embedded newline then leading whitespace.

或者(如Python 3中的版本所述):

Values can span multiple lines, as long as they are indented deeper than the first line of the value.

此功能提供了一种将值拆分并跨多行“继续”它们的方法。例如,假设您有一个名为'test.ini'的配置文件,其中包含:

[EG SECTION]<br>
EG=<br>
  item 1<br>
  item 2<br>
  item 3<br>

您可以将EG SECTIONEG的值读入一个列表,其中的代码如下:

try:
    import ConfigParser as configparser
except ImportError:  # Python 3
    import configparser

cp = configparser.ConfigParser()
cp.read('test.ini')

eg = cp.get('EG SECTION', 'EG')
print(repr(eg))  # -> '\nitem 1\nitem 2\nitem 3'

cleaned = [item for item in eg.strip().split('\n')]
print(cleaned)  # -> ['item 1', 'item 2', 'item 3']

相关问题 更多 >