Python - 在配置文件的值中使用 %s

Python - Use %s in value of config file

我使用一个配置文件(type .ini)来保存我的SQL查询,然后我通过它的键得到一个查询。一切正常,直到创建带有参数的查询,例如:

;the ini file

product_by_cat = select * from products where cat =%s

我使用:

config = configparser.ConfigParser()
args= ('cat1')
config.read(path_to_ini_file)
query= config.get(section_where_are_stored_thequeries,key_of_the_query)
complete_query= query%args

我收到错误:

TypeError: not all arguments converted during string formatting

因此它尝试在从 ini 文件中检索值时格式化字符串。 我的问题的任何提议。

你可以像这样使用format函数

ini 文件

  product_by_cat = select * from products where cat ={}

python:

 complete_query= query.format(args)

取决于 ConfigParser 的版本(Python 2 或 Python 3),您可能需要像这样将 % 加倍,否则会引发错误:

product_by_cat = select * from products where cat =%%s

尽管更好的方法是使用配置解析器的原始版本,因此 % 字符不会被解释

config = configparser.RawConfigParser()