3

我是 Python 的新手,并尝试阅读 YAML 文件。根据它的内容,我想创建 Python 对象。我正在使用 ruamel-yaml 库。就我而言,也许我有 Python-Classes Message、Signal 和 Signalgroup 等(参见示例文件)。

我的方法是读取 YAML 文件,检查给定关键字的每一行,然后创建相关对象并用数据填充它。我认为这是“老派”方法,也许有一种更有效的方法来处理文件。

也许使用函数 register_class/rep。创建标签“from_yaml”但由于键被索引它不起作用。

Message1:
Message2:
Message3:

有没有更专业的方法?

# Yaml Testfile

- ModuleName: myTestModule
- Version: 1.0
- ModuleNumbers: [96,97,98,99]


- Message1:
   Name: AO3_
   DLC: 8
   Signal1:
     Name: Temperature
     Length: 16
   Signal2:
     Name: AnalogOut3
     Length: 16
     SignalGroup1:  #Comment
        Name: app_fcex
        Type: Bitfield
        Signal1:
            Name: drive_ready
            Length: 1
        Signal2:
            Name: error_active
            Length: 1
        Signal3:
            Name: warning_active            
            Length: 1
   Signal3:
     Name: Temperatur 2
     Length: 8
     ValueTable:
        Name: TempStates
        Item0:
           Name: INIT
           Value: 1
        Item1:
           Name: RUN
           Value: 2
        Item2:
           Name: DONE
           Value: 3
        Item3:
           Name: ERROR
           Value: 4
- Message2:
   name: AO2_
   object: RX2
   DLC: 8
4

1 回答 1

2

我建议您在 YAML 文件中使用标签,并放弃使用名称为 , 的键Item1Item2替换为标记对象列表)。

很难看到您的数据的确切结构,但第一步可能是制作 YAML 文档(假设在文件中input.yaml

- ModuleName: myTestModule
- Version: 1.0
- ModuleNumbers: [96,97,98,99]


- !Message
  Name: AO3_
  DLC: 8
  Signal1:
    Name: Temperature
    Length: 16
  Signal2:
    Name: AnalogOut3
    Length: 16
    SignalGroup1:  #Comment
       Name: app_fcex
       Type: Bitfield
       Signal1:
           Name: drive_ready
           Length: 1
       Signal2:
           Name: error_active
           Length: 1
       Signal3:
           Name: warning_active
           Length: 1
  Signal3:
    Name: Temperatur 2
    Length: 8
    ValueTable:
       Name: TempStates
       items:
       - !Item
         Name: INIT
         Value: 1
       - !Item
         Name: RUN
         Value: 2
       - !Item
         Name: DONE
         Value: 3
       - !Item
         Name: ERROR
         Value: 4
- !Message
  name: AO2_
  object: RX2
  DLC: 8

并加载:

import sys
import ruamel.yaml


class Item:
    def __init__(self, name=None, value=None):
        self.name = name
        self.value = value

    @classmethod
    def from_yaml(cls, constructor, node):
        for m in constructor.construct_yaml_map(node):
            pass
        return cls(m['Name'], m['Value'])

    def __repr__(self):
        return 'Item(name={.name}, value={.value})'.format(self, self)

class Message:
    def __init__(self, name=None, DLC=None, object=None, signals=None):
        self.name = name
        self.dlc = DLC
        self.object = object
        self.signals = [] if signals is None else signals

    @classmethod
    def from_yaml(cls, constructor, node):
        for m in constructor.construct_yaml_map(node):
            pass
        if 'Name' in m:
            name = m['Name']
        elif 'name' in m:
            name = m['name']
        else:
            name = None
        object = m['object'] if 'object' in m else None
        if 'DLC' in m:
            dlc = m['DLC']
        else:
            dlc = None
        if 'signals' in m:
            signals = m['signals']
        elif 'Signal1' in m:
            x = 1
            signals = []
            while True:
                name = "Signal{}".format(x)
                try:
                    signals.append(m[name])
                except KeyError:
                    break
                x += 1
        else:
            signals = None
        return cls(name, dlc, object, signals)

    def __repr__(self):
        return 'Message(name={}, DLC={}, object={}, signals{})'.format(
            self.name, self.dlc, self.object, '[...]' if self.signals else '[]',
        )

yaml = ruamel.yaml.YAML(typ='safe')
yaml.register_class(Item)
yaml.register_class(Message)
with open('input.yaml') as fp:
    data = yaml.load(fp)

以上对密钥可用性进行了一些但有限的检查(例如规范化Namename用于!Message.

有了上面print('data')给出的(手工包装):

[{'ModuleName': 'myTestModule'}, 
 {'Version': 1.0}, 
 {'ModuleNumbers': [96, 97, 98, 99]}, 
  Message(name=Signal4, DLC=8, object=None, signals[...]), 
  Message(name=AO2_, DLC=8, object=RX2, signals[])]

print(data[3].signals[2]['ValueTable']['items'][2])给出:

Item(name=DONE, value=3)

当然应该酌情增加更多的课程。

于 2018-02-28T14:43:11.380 回答