问题描述
我正在尝试使用ConfigParser解析.conf文件,并且某些值的值中包含'%'。
以下配置示例:
[global]
workgroup = WORKGROUP
server string = %h server (Samba,Ubuntu)
当我使用RawConfigParser对此进行解析时,它将server string
设置为
%h server (Samba,Ubuntu)\n\n\n\ndns proxy = no\n\n\n\n\n\n\n\n...REST_OF_CONfig_SECTION
一堆\n
是配置选项之间的空白行。当我使用普通的ConfigParser
时,我得到一个InterpolationSyntaxError
并出现错误
'%'必须后跟'%'或'(',找到:'%h服务器(Samba,Ubuntu)\ n \ n \ n \ ndns代理=否\ n \ n \ n \ n \ n \ n \ n \ n
在将字符串传递给ConfigParser之前进行编辑(将%替换为%%)会对其进行解析,但是与RawConfigParser出现相同的问题,即它将其余选项解析为一行。
我应该如何正确解析其中包含%的值?
解决方法
请参阅文档。您必须使用%%来逃脱%
https://docs.python.org/3/library/configparser.html
[Escape]
gain: 80%% # use a %% to escape the % sign (% is the only character that needs to be escaped)
在您的情况下:
[global]
workgroup = WORKGROUP
server string = %%h server (Samba,Ubuntu)