Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

python - New lines with ConfigParser?

I have a config file using configParser:

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

My program works fine reading and processing these values.

However some of the sections are going to be quite large. I need a config file that will allow the values to be on a new line, like this:

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

In my code I have a simple function that takes a delimiter (or separator) of the values using string.split() obviously now set to comma. I have tried the escape string of which does not work.

Does anyone know if this is possible with python's config parser?
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

I would use for this:

taskStrings = list(getFromConfig(teamName, "Y","Z",","))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The ConfigParser _read() method's docstring says:

Continuations are represented by an embedded newline then leading whitespace.

Or alternatively (as the version in Python 3 puts it):

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

This feature provides a means to split values up and "continue" them across multiple lines. For example, say you had a config file named 'test.ini' which contained:

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

You could read the value of EG in the EG SECTION into a list with code like this:

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))  # -> '
item 1
item 2
item 3'

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...