如何在 configparser python 中使用 % 符号?

How to use % signs in configparser python?

我正在为我的 python 项目写一个 config.ini 文件。我想提一下列的标准日期格式。

像这样

prod_db_end_date   = 2017-01-01
prod_db_end_date_format = %Y-%m-%d

但它插入了其他内容并出错。有人可以告诉我如何使用它吗?

Error traceback - File "C:\ProgramData\Anaconda3\lib\configparser.py", line 443, in _interpolate_some
      "found: %r" % (rest,))
configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%Y-%m-%d'

您有三个选择:

  • 禁用插值,或选择不同的插值处理程序。您可以将 interpolation 选项设置为 None 以禁用整个文件的插值:

    ConfigParse(interpolation=None)
    

    参见Interpolation of values section

  • 在禁用插值的情况下访问该特定值,为 ConfigParser.get() method 设置 raw=True:

    config.get('section', 'prod_db_end_date_format', raw=True)
    
  • % 个字符加倍为 %%:

    prod_db_end_date_format = %%Y-%%m-%%d