我正在开发一个自动化工作流程的脚本。它期望CSV和磁盘映像出现在以args.input提供的目录中。
我想检查并处理所有可能的情况:没有CSV,没有磁盘映像,太多CSV,太多磁盘映像,以及任何可能的组合。
我已经写了下面的内容,它起作用,似乎是人类可读的,但它看起来非常过分和冗长 - 我有什么方法可以让它更紧凑,但仍保持其易读性?
# CONFORMANCE CHECKS
def check_conformance():
csv = glob.glob(args.input+'*.csv')
disk_image = glob.glob(args.input+'*.E01')
if len(csv) == 1:
does_csv_exist = os.path.isfile(csv[0])
elif len(csv) < 1:
does_csv_exist = False
elif len(csv) > 1:
does_csv_exist = "too many CSVs!"
if len(disk_image) == 1:
does_E01_exist = os.path.isfile(disk_image[0])
elif len(disk_image) < 1:
does_E01_exist = False
elif len(disk_image) > 1:
does_E01_exist = "too many Disk Images!"
if len(disk_image) > 1 and len(csv) > 1:
does_csv_exist = "too many CSVs!"
does_E01_exist = "too many disk images!"
return (False, does_csv_exist, does_E01_exist,)
if does_E01_exist is True and does_csv_exist is True:
return True
elif does_E01_exist is True and does_csv_exist is False:
return (False, "CSV is missing")
elif does_E01_exist is False and does_csv_exist is True:
return (False, "E01 disk image is missing")
elif does_E01_exist is False and does_csv_exist is False:
return (False, "E01 disk image AND csv are missing")
elif does_csv_exist is not True and does_csv_exist is not False:
return (False, does_csv_exist)
elif does_E01_exist is not True and does_E01_exist is not False:
return (False, does_E01_exist)
答案 0 :(得分:1)
我不确定这个功能的用途是什么,但这里有一些提示:
一个函数应该只有一个函数。您的似乎有多个 - 返回输入是否符合您的标准(True/False
)和返回某种错误字符串(str
)。你正在返回以不可预测的方式组合这两件事的元组。选择一个或另一个,或标准化元组并始终返回相同的元组(即(bool, str)
)
即使你可以为同一个变量设置多个不同的类型,你也不应该。不要在一个条件中设置布尔值,然后在另一个条件中设置字符串(请参阅:does_csv_exist
)
我会做这样的事情:
# CONFORMANCE CHECKS
# Returns a list of error strings encountered, empty list if OK
def getConformanceErrors():
csv = glob.glob(args.input+'*.csv')
disk_image = glob.glob(args.input+'*.E01')
msg = []
if len(csv) < 1:
msg.append("CSV is missing")
elif len(csv) > 1:
msg.append("Too many CSVs")
if len(disk_image) < 1:
msg.append("Disk Image is missing")
elif len(disk_image) > 1:
msg.append("Too many Disk Images")
return msg