基于cst的configparser配置编辑器
imperfect的Python项目详细描述
不完美的
这是一个用于自动编辑现有 configparser兼容的ini文件。它像CST一样工作,解析成一个树 可以编辑并回写的节点,保留空白和 评论。在
快速入门
(在测试套件中作为test_example_from_readme
进行测试)
假设您在setup.cfg
中有以下内容:
[metadata]# the package namename=imperfect# slurp the readmelong_description=file: README.md[options]packages=imperfect
您希望在中进行编辑设置long_description_content_type
[metadata]
但不在乎它去了哪里。默认值在末尾。在
如果你想控制秩序,然后又想要它呢
long_description
?现在有了差异和更多的内部。。。在
importdifflibimportimperfectimportiowithopen("setup.cfg")asf:data=f.read()conf:imperfect.ConfigFile=imperfect.parse_string(data)metadata_section=conf["metadata"]# Ignoring some whitespace for now, this looks like# long_description_content_type = text/markdown\n# [ entry ]# [ key ][eq][ value ]value=imperfect.ValueLine(whitespace_before_text='',text='text/markdown',whitespace_after_text='',newline='\n',)new_entry=imperfect.ConfigEntry(key="long_description_content_type",equals="=",value=[value],whitespace_before_equals=" ",whitespace_before_value=" ",)fori,entryinenumerate(metadata_section.entries):ifentry.key=="long_description":metadata_section.entries.insert(i+1,new_entry)breakprint(moreorless.unified_diff(data,conf.text,"config.cfg",end=""))withopen("setup.cfg","w")asf:f.write(conf.text)# orwithopen("setup.cfg","w")asf:conf.build(f)
关于空白的注记
遵循configobj使用的约定,空格通常是累积的 并存储在它后面的节点上。这对于增加 条目,但在删除它们时可能会产生意外的后果。例如
[section1]# this belongs to k1k1=foo# this belongs to k2k2=foo# k3 = foo (actually belongs to the following section)[section2]
在section1
结尾的插入将介于k2和k3注释之间。
删除section2
也会删除注释掉的k3
。在
我愿意接受改进的想法。在
格式注释
目标是尽可能与RawConfigParser
兼容,这
一些奇怪的行为包括
十年,现在可能无法改变。在
- 部门名称非常宽松。
[[x]]yy
是一个合法的剖面线,并且 产生的节名是[x
。这里的yy
总是允许的(我们保留它 但在树中),即使关闭inline_comments
。在 \r
(回车符)被认为是空白,但不是行结束符。 这是str.splitlines(True)
和list(io)
——configparser使用后者。在\t
计为单个空白。在
支持的分析选项
Option Default Imperfect supports
allow_no_value False only False
delimiters =,: only =,:
comment_prefixes #,; only #,;
empty_lines_in_values True True (False is very close to working)
测试
我们使用假设来生成可信的ini文件 RawConfigParser可以接受,我们测试是否接受,具有相同的键/值, 可以往返。在
当前仅在文本模式下发生。在
如果要测试对文件的支持,请尝试python -m imperfect.verify <filename>
为什么不
configobj
对行连续体有一种完全不同的方法- 我不知道其他人的目标是保留空白
许可证
不完美是版权Tim Hatch,并根据
麻省理工学院的执照。我在一个开放的
源代码许可证。这是我的个人存储库;您收到的许可证
我的代码来自我而不是我的雇主。有关详细信息,请参阅LICENSE
文件。在
- 项目
标签: