逐行读取解析,只获取需要的section对应的内容,section只支持顶层的字段 :param filepath: :param section: :return:
(self, filepath, section)
| 16 | |
| 17 | class YamlReader(object): |
| 18 | def read_section(self, filepath, section): |
| 19 | """ |
| 20 | 逐行读取解析,只获取需要的section对应的内容,section只支持顶层的字段 |
| 21 | :param filepath: |
| 22 | :param section: |
| 23 | :return: |
| 24 | """ |
| 25 | section_lines = [] |
| 26 | in_section = False |
| 27 | |
| 28 | with open(filepath, 'r', encoding='utf-8') as rf: |
| 29 | line = rf.readline() |
| 30 | while line: |
| 31 | if line.strip().startswith('#'): |
| 32 | # 注释行,忽略 |
| 33 | # print("[comment]%s" % line) |
| 34 | pass |
| 35 | elif line.startswith((section+':', section+' ')): |
| 36 | # print('[start]%s' % line) |
| 37 | section_lines.append(line) |
| 38 | in_section = True |
| 39 | elif in_section: |
| 40 | if line.startswith((' ', '-', '\n', '\r\n')): |
| 41 | # print('[in]%s' % line) |
| 42 | section_lines.append(line) |
| 43 | else: |
| 44 | # print('[end]%s' % line) |
| 45 | break |
| 46 | line = rf.readline() |
| 47 | if section_lines: |
| 48 | section_str = '\n'.join(section_lines) |
| 49 | section_dict = yaml.safe_load(section_str) |
| 50 | return section_dict[section] |
| 51 | else: |
| 52 | return {} |
| 53 | |
| 54 | |
| 55 | if __name__ == '__main__': |
no outgoing calls
no test coverage detected