Let us assume the following example to extend Yours for completeness:
#!/usr/bin/env python3
import argparse
...
def main():
parser = argparse.ArgumentParser()
parser.add_argument('input', nargs='?' action='store')
parser.add_argument('-l', '--length', type=int, action='store')
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()
if (args.input == None and args.length == None):
parser.print_help()
else:
print(args)
if __name__ == '__main__':
main()
Your Namespace object, mentioned by @Ben, in this example is args
. From the strings in parser.add_argument
a variable is created. You can access it through args.input
or args.length
or args.verbose
. You can verify this by executing print(args)
which will actually show something like this:
Namespace(input=None, length=None, verbose=False)
since verbose is set to True
, if present and input and length are just variables, which don't have to be instantiated (no arguments provided).
Also helpful can be group = parser.add_mutually_exclusive_group()
if you want to ensure, two attributes cannot be provided simultaneously.
For further reference, please refer to: