2

I'm trying to parse a .conf file with ConfigParser, and some of the values have a '%' in the value.

Example of the config below:

[global]
    workgroup = WORKGROUP
    server string = %h server (Samba, Ubuntu)

When I parse this using RawConfigParser, it sets server string to

%h server (Samba, Ubuntu)\n\n\n\ndns proxy = no\n\n\n\n\n\n\n\n...REST_OF_CONFIG_SECTION

Where the bunch of \n are blank lines between config options. And when I use the normal ConfigParser, I get an InterpolationSyntaxError with the error

'%' must be followed by '%' or '(', found: '%h server (Samba, Ubuntu)\n\n\n\ndns proxy = no\n\n\n\n\n\n\n\n

Editing the string before passing it to ConfigParser (replacing % with %%) parses it, but does the same issue as RawConfigParser where it parses the rest of the options as a single line.

How am I supposed to properly parse values that have a % in them?

cclloyd
  • 8,171
  • 16
  • 57
  • 104
  • The error message literally says hot to fix it: `'%' must be followed by '%'` – DYZ Oct 08 '20 at 05:57
  • @DYZ but what if that is not an option since the config file would no longer be valid for the program? (samba) – cclloyd Oct 08 '20 at 06:00

2 Answers2

3

Disable interpolation in the normal ConfigParser:

configparser.ConfigParser(interpolation=None)
0

Please refer to Documentation. you have to escape the % by using %%

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)

in your case:

[global]
workgroup = WORKGROUP
server string = %%h server (Samba, Ubuntu)
Vignesh
  • 1,553
  • 1
  • 10
  • 25
  • 1
    But what if that would make the .conf file invalid for the application it's being used for? – cclloyd Oct 08 '20 at 06:09
  • why it is going to invalid if you change the percentage? – Vignesh Oct 08 '20 at 06:14
  • It's reading specifically `smb.conf`, the configuration file for samba. Samba uses replacements with a single percent, such as %h for hostname. Doing %%h would invalidate the configuration. – cclloyd Oct 08 '20 at 06:17