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?
1 Answer
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')
-
I want to retain the option to use the names. I want to replicate the functionality I would get from a python function. Commented Oct 10, 2015 at 6:58
-
Are you able to supply both positional and optional arguments?– David CCommented Oct 10, 2015 at 7:11
-
Superficially this will be similar, but not exactly the same. You will be able to supply the values in either way. But behavior when neither is given, or when both are used may be different.– hpauljCommented Oct 11, 2015 at 0:40