好吧,如果你準備假設[process]
總是先[export]
,而且[export]
將永遠紀念Python代碼的結尾,那麼你可以預先處理ini文件將它傳遞給前去掉這部分在ConfigParser
像這樣的東西......
from ConfigParser import RawConfigParser
from StringIO import StringIO
START_PROCESS_TOKEN = '[process]'
END_PROCESS_TOKEN = '[export]'
def hacky_parse(stream):
state = 0
ini_io = StringIO()
python_io = StringIO()
for line in stream.readlines():
if state == 0:
if line.strip() == START_PROCESS_TOKEN:
state = 1
continue
ini_io.write(line)
elif state == 1:
if line.strip() == END_PROCESS_TOKEN:
ini_io.write(line)
state = 2
continue
python_io.write(line)
else:
ini_io.write(line)
ini_io.seek(0)
python_io.seek(0)
config_parser = RawConfigParser()
config_parser.readfp(ini_io)
python_code = python_io.getvalue()
return config_parser, python_code
cfg = """
[load]
files=a,b,c
[process]
while 1:
do_stuff()
[export]
files=x,y,z
"""
my_stream = StringIO(cfg)
config_parser, process_code = hacky_parse(my_stream)
print 'The value of "files" in section "load" is...'
print config_parser.get('load', 'files')
print
print 'The raw Python code is...'
print process_code
...這將產生...
The value of "files" in section "load" is...
a,b,c
The raw Python code is...
while 1:
do_stuff()
...顯然,對於事端一個真正的文件對象代替my_stream
摹狀...
my_stream = open('config.ini', 'r')
更新
嗯,有一個爲你的代碼,例如破損的可能性增加,如果線路[load]
出現在Python代碼。
我只是想到另一種選擇。如果你做的配置文件看起來像一個RFC822消息...
Load-Files: a,b,c
Export-Files: x,y,z
# Python code starts here
while 1:
do_stuff()
...你可以分析它很簡單,像這樣...
import email
cfg = \
"""Load-Files: a,b,c
Export-Files: x,y,z
# Python code starts here
while 1:
do_stuff()
"""
msg = email.message_from_string(cfg)
print msg.items()
print
print msg.get_payload()
..這...產量
[('Load-Files', 'a,b,c'), ('Export-Files', 'x,y,z')]
# Python code starts here
while 1:
do_stuff()
我的意思是,你不必使用嚴格的RFC822格式,但把Python代碼在配置文件末尾的優點是,有沒有機會,在代碼中什麼事情都可能與之發生衝突您用於文件其餘部分的格式。
請注意''[export]'和'files = x,y,z'在Python中都是有效表達式,所以如何確定'[process]'節的結尾?我想這裏的答案是'ConfigParser'不幸的是,除非有一些限制可以放在''上。 –
Aya
2013-05-03 17:25:48
@Aya我認爲你是對的。我相信我可以假設'[export]'實際上是'[process]'部分的結尾。但是,這仍然是一個黑客。 – 2013-05-03 17:58:05