如果您的输入格式是一些未格式化的SQL(没有换行符和缩进空格),就像您似乎从输出(2)中 获取的那样,您将 永远不会 自动获得良好的输出:
import yamlsql = ("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 descriptionn FROM ...."}
我建议您采用其他方法,并结合ruamel.yaml(我是PyYAML增强版的作者)安装sqlparse或format-
sql之类的sql格式化程序,该格式程序支持多行文字字符串往返。在一点帮助下,它也可以用于生成正确且更好(如果不是更好)的YAML输出。
你可以做:
import ruamel.yamlfrom ruamel.yaml.scalarstring import PreservedScalarStringimport sqlparsesql = ("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").enpre('utf-8')app_config = dict(sql=PreservedScalarString(fsql))print ruamel.yaml.dump(app_config, Dumper=ruamel.yaml.RoundTripDumper)
并获得带有保留的换行符的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 ....
希望距离您想要的足够近。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)