The argparse package does a great job when dealing with command line arguments. I'm wondering however if there is any way to ask argparse to check for file extension (e.g ".txt"). The idea would be to derived one the class related to argparse.FileType. I would be interested in any suggestion.
Keep in mind that I have more than 50 subcommands in my program all having there own CLI. Thus, I would be interest in deriving a class that could be imported in each of them more than adding some uggly tests in all my commands.
Thanks a lot.
# As an example one would be interested in turning this...
parser_grp.add_argument('-o', '--outputfile',
help="Output file.",
default=sys.stdout,
metavar="TXT",
type=argparse.FileType('w'))
# Into that...
from somewhere import FileTypeWithExtensionCheck
parser_grp.add_argument('-o', '--outputfile',
help="Output file.",
default=sys.stdout,
metavar="TXT",
type=FileTypeWithExtensionCheck('w', '.[Tt][Xx][Tt]$'))
argparsedeveloper includedFileTypeto help with small scripts that routinely take input/output files. But I think it's most valuable as a model for writing your owntypeclass. The key thing is thattypehas to be a callable, whether that's a function or the__call__of a class.FileTypetoo closely is that it opens the file or even creates a new one. In bigger scripts it is better to operate on a file using thewithcontext. So consider atypethat checksfilenameformat, but doesn't actually the file.FileContextclass that can check for a file's existence or form, but returns an unopened file, one that can be used directly in awithcontext. Handling stdin/out was tricky, since you don't normally want to close those.