我想用argparse指定几个文件扩展名。用argparse指定文件扩展名
我试过下面的代码,但它不起作用。如何使用argparse指定多个文件扩展名?
parser.add_argument('file', action = 'store', type = argparse.FileType('r'), choices=["*.aaa", "*.bbb"])
编辑:我发现使用字符串类型,而不是文件类型的我自己的解决方案:
def input_ok(string):
if not os.path.exists(string):
raise argparse.ArgumentTypeError("Filename %r doesn\'t exists in this directory." % string)
if string[-4:] != ".aaa" and string[-4:] != ".bbb":
raise argparse.ArgumentTypeError("%r is not a .aaa or a .bbb file." % string)
return string
...
parser.add_argument('input_path', action = 'store',
type = input_ok, #argparse.FileType('r'), #choices=["*.stl", "*.csv"])
'argparse'为您提供了一些参数验证工具,但并不要求您使用它们。 'FileType'是一个方便的功能,用于通用脚本应用程序。如果它不适合您的应用程序,则不必使用它。 “选择”也一样。 – hpaulj