![](/img/trans.png)
[英]Python 2.x - ConfigParser stripping blank lines in multiline value
[英]How to specify a unicode and other escaped literals to Python 2.x ConfigParser
我正在使用ConfigParser來讀取配置文件。
我希望配置文件保持ASCII / ANSI,但我想在其中一個配置選項中傳遞一個unicode文字(在python字面意義上):
[flatfile]
datafile_encoding = utf16
delimiter= u'\u2016'
# also this should be parsable too:
# delimiter= '\t'
我的結果是:
import ConfigParser, io
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.read(filename)
flatfile_config = {}
for item in config.items('flatfile'):
flatfile_config[item[0]] = item[1]
assert flatfile_config['delimiter'] == u'\u2016'
#assert flatfile_config['delimeter'] == '\t'
f = io.open(datafile, mode='r', encoding=flatfile_config['datafile_encoding'])
row = f.readline()
row_split = row.strip('\n').split(flatfile_config['delimiter'])
我不想創建一個in-python查找表來處理配置文件分隔符選項中的文字值(因為我正在使用配置文件)。
如果您希望以與Python相同的方式評估任何Python文本,則函數ast.literal_eval
執行您想要的操作:
>>> s = r"""u'\u2016'"""
>>> print s
u'\u2016'
>>> print ast.literal_eval(s)
‖
如果你想確保它是一個字符串或只 Unicode的文字,所以用戶不能混淆你delimiter=42
,你最好的辦法是literal_eval
然后鍵入檢查:
val = ast.literal_eval(s)
if not isinstance(val, basestring):
raise BadUserError("Why are you giving me {} when I wanted a string?".format(s))
更詳細:
安全地評估表達式節點或包含Python表達式的Unicode或Latin-1編碼的字符串。 提供的字符串或節點可能只包含以下Python文字結構:字符串,數字,元組,列表,dicts,布爾值和None。
這可以用於安全地評估包含來自不可信來源的Python表達式的字符串,而無需自己解析值。
如果你想知道不信任來源的擔心是什么,想象你剛剛使用eval
,它適用於任何Python表達式,我把它放在配置文件中:
delimiter=__import__('os').system('rm -rf /')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.