2

我有一个功能:

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 转储实用程序和转义字符组合有关。

感谢期待!

4

2 回答 2

3

根据您的预期输出,第二项不是字符串而是列表。因此,为了在 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 中单引号字符串中的双单引号仅表示一个单引号

额外的。不要使用:

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

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

for item in config_list:
  # ...
于 2016-01-11T10:48:53.100 回答
1

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

复制您的程序,使用重新加载 YAML 文件yaml.load表明它已正确重建字符串,如预期的那样:

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 在列表项中转义单引号的方式。

于 2016-01-11T10:52:32.817 回答