我想使用argparse指定几个文件扩展名。
我尝试了下面的代码,但它不起作用。如何使用argparse指定多个文件扩展名?
我尝试了下面的代码,但它不起作用。如何使用argparse指定多个文件扩展名?
parser.add_argument('file', action = 'store', type = argparse.FileType('r'), choices=["*.aaa", "*.bbb"])
编辑:我已经找到了自己的解决方案,使用字符串类型而不是FileType:
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
是一个方便的功能,旨在用于常见的脚本应用程序。如果不适合您的应用程序,则无需使用它。choices
同样如此。 - hpaulj