Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python argparse named positional arguments?

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?

like image 992
capybaralet Avatar asked Oct 10 '15 06:10

capybaralet


1 Answers

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')
like image 132
David C Avatar answered Oct 22 '22 23:10

David C