Specifying default filenames with argparse, but not opening them on --help?

后端 未结 3 1485
日久生厌
日久生厌 2021-02-07 17:05

Let\'s say I have a script that does some work on a file. It takes this file\'s name on the command line, but if it\'s not provided, it defaults to a known filename (conte

3条回答
  •  萌比男神i
    2021-02-07 17:49

    You could subclass argparse.FileType:

    import argparse
    import warnings
    
    class ForgivingFileType(argparse.FileType):
        def __call__(self, string):
            try:
                super(ForgivingFileType,self).__call__(string)
            except IOError as err:
                warnings.warn(err)
    
    parser = argparse.ArgumentParser(description='my illustrative example')
    parser.add_argument('--content', metavar='file', 
                         default='content.txt', type=ForgivingFileType('r'),
                         help='file to process (defaults to content.txt)')
    args = parser.parse_args()
    

    This works without having to touch private methods like ArgumentParser._parse_known_args.

提交回复
热议问题