1

I would like to get the dest values for all the arguments defined for the parser. I.e. in the case of:

parser = argparse.ArgumentParser()
parser.add_argument('arg1')
parser.add_argument('arg2')
parser.add_argument('arg3')
parser.add_argument('arg4')

I would like to return ['arg1', 'arg2', 'arg3', 'arg4'].

parser.parse_args() takes stuff from sys.argv which is not what I'm looking for. How can I achieve this?

Sterling Butters
  • 1,024
  • 3
  • 20
  • 41
  • `parser.parse_args` accepts an argument (list of strings) to use instead of `sys.stdin`, if you want to provide some arguments manually (this doesn't answer your question about getting `dest` values, just a comment on your last sentence) – STerliakov Jun 16 '23 at 18:42
  • 1
    You have three different statements all saying different things. Please clarify what your goal is if not this> https://stackoverflow.com/questions/38853812/how-to-use-python-argparse-with-args-other-than-sys-argv – Hein Gertenbach Jun 16 '23 at 18:51

2 Answers2

1

Though you don't typically need it, add_argument returns an instance of the Action subclass used to implement the argument. Among other things, these objects have a dest attribute containing the string you want.

For example,

import argparse

parser = argparse.ArgumentParser()
a1 = parser.add_argument('arg1')
a2 = parser.add_argument('arg2')
a3 = parser.add_argument('arg3')
a4 = parser.add_argument('arg4')
     
destinations = [x.dest for x in [a1, a2, a3, a4]])

parser._actions contains a list of all arguments defined for the parser, including things like --help, so that may also be of use.

chepner
  • 497,756
  • 71
  • 530
  • 681
1
In [1]: import argparse    
In [2]: parser = argparse.ArgumentParser()
   ...: parser.add_argument('arg1')
   ...: parser.add_argument('arg2')
   ...: parser.add_argument('arg3')
   ...: parser.add_argument('arg4')

Since these are all required positionals, we can call parse_args with:

In [4]: parser.parse_args('1 2 3 4'.split())
Out[4]: Namespace(arg1='1', arg2='2', arg3='3', arg4='4')

The parser maintains a list of the actions (arguments) that you defined. Their dest can be listed with:

In [5]: [a.dest for a in parser._actions]
Out[5]: ['help', 'arg1', 'arg2', 'arg3', 'arg4']

That list includes the 'help' that was added by default.

Another list, derived from the args (converted to a dict)

In [6]: list(vars(parser.parse_args('1 2 3 4'.split())).keys())
Out[6]: ['arg1', 'arg2', 'arg3', 'arg4']

You could also collect your own list of actions (some companies don't like you to access the "private" attributes like '_actions', though Python has a loose concept of public v private variables).

In [9]: parser = argparse.ArgumentParser()
   ...: a1=parser.add_argument('arg1')
   ...: a2=parser.add_argument('arg2')
   ...: a3=parser.add_argument('arg3')
   ...: a4=parser.add_argument('arg4')

In [10]: [a.dest for a in [a1,a2,a3,a4]]
Out[10]: ['arg1', 'arg2', 'arg3', 'arg4']
hpaulj
  • 221,503
  • 14
  • 230
  • 353