Is there a way to make python's argparse.ArgumentParser treat command line arguments the way python functions treat arguments? So that arguments can be passed without their name?
See the example with "integers" in the documentation. Don't include any hyphens and the argument will be treated as a positional argument.
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('first_supplied_argument', help='help')
>>> parser.add_argument('second_supplied_argument', help='help')
>>> args = parser.parse_args(['1', '2'])
Namespace(first_supplied_argument='1', second_supplied_argument='2')
Edit based on comment:
Are you able to supply both positional and optional arguments? I think you will still need to supply at least one positional argument.
parser = argparse.ArgumentParser()
parser.add_argument('--first', help='help')
parser.add_argument('first', nargs='?', help='help')
parser.add_argument('--second', help='help')
parser.add_argument('second', nargs='?', help='help')
print parser.parse_args(['1', '2'])
print parser.parse_args(['1', '--second', '2'])
print parser.parse_args(['--first', '1', '--second', '2']) # doesn't work
print parser.parse_args(['', '--first', '1', '--second', '2']) # probably not what you want to do
Output:
Namespace(first='1', second='2')
Namespace(first='1', second='2')
Namespace(first=None, second=None) # doesn't work
Namespace(first='1', second='2')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With