>>> with open('args.txt', 'w') as fp:
... fp.write('-f\nbar')
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
>>> parser.add_argument('-f')
>>> parser.parse_args(['-f', 'foo', '@args.txt'])
Namespace(f='bar')
>>> parent_parser = argparse.ArgumentParser(add_help=False)>>>parent_parser.add_argument('--parent', type=int) >>> foo_parser =argparse.ArgumentParser(parents=[parent_parser]) >>> foo_parser.add_argument('foo')>>> foo_parser.parse_args(['--parent', '2', 'XXX']) Namespace(foo='XXX', parent=2) >>>bar_parser = argparse.ArgumentParser(parents=[parent_parser]) >>>bar_parser.add_argument('--bar') >>> bar_parser.parse_args(['--bar', 'YYY'])Namespace(bar='YYY', parent=None)
ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parse_args(). The action keyword argument specifies how the command-line arguments should be handled. The supported actions are:
-
'store' - This just stores the argument’s value. This is the default action. For example:
>>> parser = argparse.ArgumentParser()
-
>>> parser.add_argument('--foo')
-
>>> parser.parse_args('--foo 1'.split()) Namespace(foo='1')
-
'store_const' - This stores the value specified by the const keyword argument. (Note that the const keyword argument defaults to the rather unhelpful None.) The 'store_const'action is most commonly used with optional arguments that specify some sort of flag. For example:
>>> parser = argparse.ArgumentParser()
-
>>> parser.add_argument('--foo', action='store_const', const=42)
-
>>> parser.parse_args('--foo'.split()) Namespace(foo=42)
-
'store_true' and 'store_false' - These are special cases of 'store_const' using for storing the values True and False respectively. In addition, they create default values ofFalse and True respectively. For example:
>>> parser = argparse.ArgumentParser()
-
>>> parser.add_argument('--foo', action='store_true')
-
>>> parser.add_argument('--bar', action='store_false')
-
>>> parser.add_argument('--baz', action='store_false')
-
>>> parser.parse_args('--foo --bar'.split()) Namespace(bar=False, baz=True, foo=True)
-
'append' - This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. Example usage:
>>> parser = argparse.ArgumentParser()
-
>>> parser.add_argument('--foo', action='append')
-
>>> parser.parse_args('--foo 1 --foo 2'.split()) Namespace(foo=['1', '2'])
-
'append_const' - This stores a list, and appends the value specified by the constkeyword argument to the list. (Note that the const keyword argument defaults to None.) The'append_const' action is typically useful when multiple arguments need to store constants to the same list. For example:
>>> parser = argparse.ArgumentParser()
-
>>> parser.add_argument('--str', dest='types', action='append_const',const=str)
-
>>> parser.add_argument('--int', dest='types', action='append_const',const=int)
-
>>> parser.parse_args('--str --int'.split()) Namespace(types=[, ])
-
'count' - This counts the number of times a keyword argument occurs. For example, this is useful for increasing verbosity levels:
>>> parser = argparse.ArgumentParser()
-
>>> parser.add_argument('--verbose', '-v', action='count')
-
>>> parser.parse_args('-vvv'.split()) Namespace(verbose=3)
-
'help' - This prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. SeeArgumentParser for details of how the output is created.
-
'version' - This expects a version= keyword argument in the add_argument() call, and prints version information and exits when invoked:
>>> import argparse
-
>>> parser = argparse.ArgumentParser(prog='PROG')
-
>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
-
>>> parser.parse_args(['--version']) PROG 2.0
You can also specify an arbitrary action by passing an object that implements the Action API. The easiest way to do this is to extend argparse.Action, supplying an appropriate __call__method. The __call__ method should accept four parameters:
- parser - The ArgumentParser object which contains this action.
- namespace - The Namespace object that will be returned by parse_args(). Most actions add an attribute to this object.
- values - The associated command-line arguments, with any type conversions applied. (Type conversions are specified with the type keyword argument to add_argument().)
- option_string - The option string that was used to invoke this action. Theoption_string argument is optional, and will be absent if the action is associated with a positional argument.
An example of a custom action:
>>> class FooAction(argparse.Action):
... def __call__(self, parser, namespace, values, option_string=None):
... print '%r %r %r' % (namespace, values, option_string)
... setattr(namespace, self.dest, values)
...
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=FooAction)
>>> parser.add_argument('bar', action=FooAction)
>>> args = parser.parse_args('1 --foo 2'.split())
Namespace(bar=None, foo=None) '1' None Namespace(bar='1', foo=None) '2' '--foo'
>>> args Namespace(bar='1', foo='2')
这个复杂的代码,最后输出的帮助信息是(只要命令行有-h选项就会输出帮助信息并退出哦)