【问题标题】:writing strings that have quotes correctly in python在python中正确编写带引号的字符串
【发布时间】:2021-10-13 07:13:19
【问题描述】:

我有一个包含以下行的 Dockerfile:

LABEL "com.datadoghq.ad.logs"='[{"source": "mysource", "name": "myservicename"}]'

我有一个 python 脚本,我想读取这个 LABEL 值(“LABEL”之后的所有内容并将其添加到 yaml 文件中。这是我的脚本:

#!/usr/bin/python3
import yaml

def _extract_dockerfile_labels():
    labels = []
    with open("testing/dockerfile") as dockerfile:
        for line in dockerfile.readlines():
            if line.startswith('LABEL'):
                label_val = line.replace("LABEL ","", 1)
                labels.append(label_val.rstrip()). # rstrip() gets rid of the newline
    with open("output.yml", "w+") as out_file:
        yaml.dump(labels, out_file, default_flow_style=False)

_extract_dockerfile_labels()

输出文件如下所示:

- '"com.datadoghq.ad.logs"=''[{"source": "mysource", "name": "myservicename"}]'''

我需要的是:

- "com.datadoghq.ad.logs"='[{"source": "mysource", "name": "myservicename"}]'

如何在不添加额外引号的情况下完成这项工作?

【问题讨论】:

    标签: python yaml escaping


    【解决方案1】:

    我猜问题是您使用yaml.dump() 函数进行输出,它将对象输出为 YAML 文档。它的 YAML 符号字符串有引号。
    对于标准 python 输出,请尝试使用out_file.write(labels),然后关闭文件。
    请注意,您的字符串当前未被解析为字典,因此被解释为纯字符串。因此,如果您打算将其解析为对象,则应先自己进行。
    你的编码格式对我来说并不熟悉,也许有一个可用的解析库。要将其转换为 YAML 格式,您应该考虑使用如下内容:
    labels = labels.replace("='[{", ":\n- ").replace(", ", "\n- ").replace("}]'", "")

    【讨论】:

    • out_file.write 将不起作用,因为在我的代码库中,此结果实际上只是最终转储到 yaml 文件中的元素之一。我看到你编辑了你的答案,但我确实看到了使用安全加载提到的原始答案。一个问题是无法将值加载到 yaml 中,但是 safe_load 最终成为我提出的解决方案的重要组成部分。
    • @Jashua 是的,你可以在将字符串转换为 YAML 格式后使用 yaml.safe_load()。
    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多