gpt4 book ai didi

python - 转义字符和字符串

转载 作者:行者123 更新时间:2023-11-28 22:39:28 25 4
gpt4 key购买 nike

我有一个函数:

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:
# ...

关于python - 转义字符和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34718323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com