Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python YAML-用值替换变量?_Python_Yaml - Fatal编程技术网

Python YAML-用值替换变量?

Python 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

考虑以下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_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作为您的问题的解决方案,答复如下: