环境

  • 开发环境:Mac 10.15.6(理论上适用于三大系统)
  • python:3.7.7
  • 依赖:pyyaml

上菜

import os
import sys
import yaml
import argparse

parser = argparse.ArgumentParser(
        description="A tool to find the fatal error in the yaml file.")
parser.add_argument(
    '-d', '--dir',
    type=str,
    required=True,
    help="The directory's name which contains yaml files")
args = parser.parse_args()

if not os.path.isdir(args.dir):
    sys.exit('The dir name you specified does not exist.')

for yml in os.listdir(args.dir):
    with open(args.dir + '/' + yml) as f:
        try:
            yaml.safe_load(f)
            print('{}: OK\n'.format(yml))
        except Exception as e:
            print("The yaml file of [{}] has a fatal error,\nwhich is as below:\n".format(yml))
            print(str(e) + '\n')

部署&使用

安装依赖

sudo pip3 install pyyaml

使用

usage: t.py [-h] -d DIR

A tool to find the fatal error in the yaml file.

optional arguments:
  -h, --help         show this help message and exit
  -d DIR, --dir DIR  The directory's name which contains yaml files

实战效果

分享一个检查yaml文件是否有语法错误的脚本

写在最后

如果你对python生态比较陌生,不知道怎么安装依赖,可以联系本人打包windows、Linux和Mac三大系统对应的可执行二进制单文件,无需解决依赖,一键部署,有不太明白的欢迎评论留言哦~