转义字符和字符串

escape characters and strings

我有一个函数:

def set_localrepo(self):

    stream = open("file1.yml", "r")
    results = yaml.load(stream)
    run_cmd = results["parameters"]["tag"]["properties"]
    config_list = ( 'sleep 200', '[sh, -xc, \"echo test\'  test\' >> /etc/hosts\"]')
    for i in range(len(config_list)):
        run_cmd.append(config_list[i])
    stream.close()
    with open("f2.yml", "w") as yaml_file:
        yaml_file.write(yaml.dump(results, default_flow_style=False, allow_unicode=True))
    yaml_file.close()    

在这个文件中,我有一个 file1.yml 骨架,我从那里处理列表中的内容并将其写入 f2.yml。

预期输出应如下所示:

        properties:
        - sleep 200 
        - [sh, -xc, "echo $repo_server'  repo-server' >> /etc/hosts"]

但它看起来像这样:

        properties:
        - sleep 200 
        - '[sh, -xc, "echo $repo_server''  repo-server'' >> /etc/hosts"]'

我已经尝试了双 \、单 \ 等的多种组合,但它确实如我所愿。

请告知如何解决此问题。我怀疑它与 YAML 转储实用程序和转义字符组合有关。

感谢期待!

根据您的预期输出,第二项不是字符串而是列表。因此,为了在 Python 中正确序列化,这也必须是一个列表(或元组)。这意味着您的 config_list 应该如下所示:

( 'sleep 200', ['sh', '-xc', '"echo test\'  test\' >> /etc/hosts"'] )

此更改后,输出将是:

parameters:
  tags:
    properties:
    - sleep 200
    - - sh
      - -xc
      - '"echo test''  test'' >> /etc/hosts"'

因为你禁用了 default_flow_style 你有那个奇怪的嵌套列表,它相当于:

parameters:
  tags:
    properties:
    - sleep 200
    - [sh, -xc, '"echo test''  test'' >> /etc/hosts"']

如果你担心你的单引号是正确的,因为在 YAML means one single quote only.

中,双引号 在单引号字符串中

额外。不要使用:

for i in range(len(config_list)):
  item = config_list[i]
  # ...

相反,使用更简单的迭代模式:

for item in config_list:
  # ...

我不是 YAML 专家,但我认为这是预期的行为。

使用 yaml.load 对 YAML 文件进行 re-loading 的程序复制显示它已正确重建字符串,如预期的那样:

import yaml

config_list = ( 'sleep 200', '[sh, -xc, "echo $test\'  test\' >> /etc/hosts"]')
results = {'properties': []}
run_cmd = results['properties']
for i in range(len(config_list)):
    run_cmd.append(config_list[i])

with open("f2.yml", "w") as yaml_file:
    yaml_file.write(yaml.dump(results, default_flow_style=False, allow_unicode=True))

yaml_file.close()

yaml_file2 = open('f2.yml', 'r')
data = yaml_file2.read()
print(yaml.load(data))

这会产生

的输出
{'properties': ['sleep 200', '[sh, -xc, "echo $test\'  test\' >> /etc/hosts"]']}

这正是您所期望的。在外部使用单引号并在内部使用 '' 必须是 YAML 转义列表项中的 single-quote 的方式。