Python YAML-用值替换变量?
考虑以下yamlPython YAML-用值替换变量?,python,yaml,Python,Yaml,考虑以下yaml hadoop: storage: '/x/y/z/a/b' streaming_jar_path: '/x/c/d/f/r/*.jar' commands: mkdir: 'hadoop dfs -mkdir dir' copyFromLocal: 'hadoop dfs -copyFromLocal from_path to_path' run: 'hadoop jar $streaming_jar_pa
hadoop:
storage: '/x/y/z/a/b'
streaming_jar_path: '/x/c/d/f/r/*.jar'
commands:
mkdir: 'hadoop dfs -mkdir dir'
copyFromLocal: 'hadoop dfs -copyFromLocal from_path to_path'
run: 'hadoop jar $streaming_jar_path -mapper mapper_path -reducer reducer_path -input hdfs_input -output hdfs_output'
我想将streaming\u jar\u path
的值替换为$streaming\u jar\u path
,我该怎么做
我知道我们可以使用和(锚定)
合并哈希值,但这里我只想更改一个值
如果这是一件小事,我很抱歉,我对YAML
谢谢这应该是一个读取文件、编辑数据和写回文件的简单过程
import yaml
infile = 'input.yaml'
outfile = 'output.yaml'
#read raw yaml data from file into dict
with open(infile, 'r') as f:
data = yaml.load(f.read())
#make changes to dict
data['hadoop']['streaming_jar_path'] = '$streaming_jar_path'
#write dict back to yaml file
with open(outfile, 'w') as f:
f.write(yaml.dump(data))
您可以重新构造YAML
文件并使用执行
commands.yml:
- hosts: localhost
vars:
streaming_jar_path: '/x/c/d/f/r/*.jar'
tasks:
- name: mkdir
shell: "hadoop dfs -mkdir dir"
- name: copyFromLocal
shell: "hadoop dfs -copyFromLocal from_path to_path"
- name: run
shell: "hadoop jar {{ streaming_jar_path }} -mapper mapper_path -reducer reducer_path -input hdfs_input -output hdfs_output"
然后只需运行ansible playbook
即可执行shell命令:
ansible-playbook commands.yml
您想在YAML中将streaming\u jar\u path
重命名为streaming\u jar\u path\u substitute
,还是将名为streaming\u jar\u path\u substitute
的Python变量的值赋给streaming\u jar\u path
?将streaming\u jar\u path的值赋给streaming\u jar\u path\u substitute作为您的问题的解决方案,答复如下: