0

我尝试在 R 中编写一个脚本,这需要修改一个.cwl文件。以文件为例test.cwl

#!/usr/bin/env cwl-runner

cwlVersion: v1.0
class: Workflow

requirements:
  - class: StepInputExpressionRequirement

inputs:
  - id: submissionId
    type: int

outputs: []

理想情况下,我想阅读test.cwl并修改inputs$id. 最后,写出一个更新的new_test.cwl文件。但是,我找不到test.cwl在 R 中读取此文件的方法?我试过tidycwl,但它只能读取带有ymaljson扩展名的文件。

如果 python 中的任何包都可以解决问题,我也很乐意将它与reticulate.

谢谢!

4

3 回答 3

1

安装 PyYAML:

pip install PyYAML==6.0

运行此脚本:

import yaml
# Read file
with open("test.cwl", 'r') as cwl_file:  
    cwl_dict = yaml.safe_load(cwl_file)

# Write file
with open("test-new.cwl", 'w') as cwl_file:
    cwl_dict["inputs"] = [{"id" : 2, "type": "ABC"}]
    yaml.dump(cwl_dict, cwl_file)

稍后由 WenliL建议编辑 以修复标识

pip install ruamel.yaml
from ruamel.yaml import YAML

yaml = YAML()
with open("test.cwl", 'r') as cwl_file:
    cwl_dict = yaml.load(cwl_file)

with open("test-new.cwl", 'w') as cwl_file:
    cwl_dict["inputs"] = [{"id": 2, "type": "ABC"}]
    yaml.indent(mapping=2, sequence=4, offset=2)
    yaml.dump(cwl_dict, cwl_file)

输出:

cwlVersion: v1.0
class: Workflow
requirements:
  - class: StepInputExpressionRequirement
inputs:
  - id: 2
    type: ABC
outputs: []
于 2022-01-22T14:49:14.930 回答
0

根据@nuno-carvalho 的回答,我添加了 ruamel.yaml 来修复数组的缩进:

pip install ruamel.yaml
from ruamel.yaml import YAML

yaml = YAML()
with open("test.cwl", 'r') as cwl_file:
    cwl_dict = yaml.load(cwl_file)

with open("test-new.cwl", 'w') as cwl_file:
    cwl_dict["inputs"] = [{"id": 2, "type": "ABC"}]
    yaml.indent(mapping=2, sequence=4, offset=2)
    yaml.dump(cwl_dict, cwl_file)

输出:

cwlVersion: v1.0
class: Workflow
requirements:
  - class: StepInputExpressionRequirement
inputs:
  - id: 2
    type: ABC
outputs: []

我不擅长python,请感觉建议

于 2022-01-22T14:46:49.437 回答
0
with open(cwl_file_path, 'r') as cwl_file:  
    cwl_dict = yaml.safe_load(cwl_file)

yaml 的更多信息:

https://pyyaml.org/wiki/PyYAMLDocumentation

于 2022-01-22T14:50:22.067 回答