如果您的输入格式是一些未格式化的 SQL(没有换行符和缩进空格),就像您似乎从输出 (2) 中获取的那样,您将never自动获得不错的输出:
import yaml
sql = ("SELECT DISTINCT p.id_product, "
"p.price AS price, "
"sp.reduction AS discount, "
"sp.reduction_type AS discount_type, "
"pl.description_short AS description "
"FROM ....")
app_config = dict(sql=sql)
print yaml.dump(app_config)
会给你:
{sql: 'SELECT DISTINCT p.id_product, p.price AS price, sp.reduction AS discount, sp.reduction_type
AS discount_type, pl.description_short AS description FROM ....'}
正如你发现的那样。你可以尝试
使用换行符和缩进手动格式化字符串
app_config = dict(sql="""\
SELECT DISTINCT p.id_product,
p.price AS price,
sp.reduction AS discount,
sp.reduction_type AS discount_type,
pl.description_short AS description
FROM ....""")
print yaml.dump(app_config)
但输出也好不到哪儿去:
{sql: "SELECT DISTINCT p.id_product,\n p.price AS price,\n \
\ sp.reduction AS discount,\n sp.reduction_type AS discount_type,\n\
\ pl.description_short AS description\n FROM ...."}
我建议你采取不同的方法并安装一个 sql 格式化程序,例如sqlparse https://pypi.python.org/pypi/sqlparse or 格式-sql https://pypi.python.org/pypi/format-sql结合鲁梅尔.yaml https://pypi.python.org/pypi/ruamel.yaml(我是 PyYAML 增强版的作者),它支持多行文字字符串往返。借助一点帮助,它还可以用于生成正确且外观更好(如果不是更好)的 YAML 输出。
你可以做:
import ruamel.yaml
from ruamel.yaml.scalarstring import PreservedScalarString
import sqlparse
sql = ("SELECT DISTINCT p.id_product, "
"p.price AS price, "
"sp.reduction AS discount, "
"sp.reduction_type AS discount_type, "
"pl.description_short AS description "
"FROM ....")
fsql = sqlparse.format(sql, reindent=True, keyword_case="upper").encode('utf-8')
app_config = dict(sql=PreservedScalarString(fsql))
print ruamel.yaml.dump(app_config, Dumper=ruamel.yaml.RoundTripDumper)
并得到一个带有保留换行符的 YAML 文字标量 http://yaml.org/spec/1.2/spec.html#%7C%20literal%20style//:
sql: |-
SELECT DISTINCT p.id_product,
p.price AS price,
sp.reduction AS discount,
sp.reduction_type AS discount_type,
pl.description_short AS description
FROM ....
希望足够接近你想要的。