How do I return a parameter string using argparse?

parser = argparse.ArgumentParser() parser.add_argument("-p", "--pattern", help="Pattern file") args = parser.parse_args() 

Now you can return the string "--pattern" from args ? I need a line so that I can build a cmd list to go to Popen, like Popen(['some_other_program', args.pattern.option_string, args.pattern], ...) without repeating it (and should support it in two places ) ( Popen(['some_other_prog', '--pattern', args.pattern], ...) ).

I need to create a shell for another program. Some of the arguments must be passed to the wrapped program (via Popen), and some by the shell.


Is there a better way than in the following example?

 pass_1 = '--to-be-passed' parser = argparse.ArgumentParser() parser.add_argument("-p", pass_1, help="Pass me on") parser.add_argument("-k", "--arg-for-wrapper") args = parser.parse_args() ... process = Popen(['wrapped_program', pass_1, args.pass_1], ...) ... 

This method of storing arguments in variables is not very good, like:

  • Keeping short parameters together with long options becomes difficult.
  • Popen , if calling another function requires passing these variables (or their name) to the function. This seems redundant, as the args passed to it should be sufficient.
+6
source share
3 answers

Add dest to your add_argument call.

 parser.add_argmument("p", "--pattern", dest="pattern", help="your help text") args = parser.parse_args() args = vars(args) 

You can reference a pattern with args["pattern"] .

+2
source

Deleted answers and comments indicate some confusion about what you want. Therefore, I will add to this confusion.

Typically, the parser does not write a string of options. However, it is provided to the Action __call__ method. That way, a custom Action class could save it. The custom class FooAction example in argparse docs illustrates this.

If I define this subclass of action:

 In [324]: class PassThru(argparse._StoreAction): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, [values, option_string]) In [324]: p.add_argument('-o','--other',action=PassThru) 

The options string is written along with the value ('-o' or '--other'):

 In [322]: p.parse_args('-p test -o teseting'.split()) Out[322]: Namespace(other=['teseting', '-o'], pass_me_on='test') In [323]: p.parse_args('-p test --other teseting'.split()) Out[323]: Namespace(other=['teseting', '--other'], pass_me_on='test') 

Obviously, option_string and value can be written in a different order, in the dictionary, as separate attributes in the namespace, etc.


There are other ways to pass parameters to another program, especially if the packet parser does not need to be processed.

argparse receives arguments from sys.argv[1:] and does not change it. Therefore, even if your parser uses some arguments, you can pass this list to popen (in whole or in part).

In the argparse docs document, there is an example under nargs=REMAINDER to parse some arguments for yourself and collect the rest to go to another program. This is their example:

 >>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('--foo') >>> parser.add_argument('command') >>> parser.add_argument('args', nargs=argparse.REMAINDER) >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())) Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B') 

So you can call popen something like

 plist = ['wrapped_program'] plist.extend(args.args) popen(plist, ...) 

Using parse.parse_known_args can also be used to collect unverified words in the Advanced list. This section of the document talks about passing these lines to another program (how you do it). Unlike the case of REMAINDER, additional material should not be the last.

These works, of course, only if this analyzer does not require --pattern for itself. If he analyzes it, he will not appear in REMAINDER or additional functions. In this case, you will have to add it back to the list you give popen

I would fine-tune your parser like this:

 pass_1 = 'passed' # without the -- or internal - dpass_` = '--'+pass_ parser = argparse.ArgumentParser() parser.add_argument("-p", dpass_1, help="Pass me on") parser.add_argument("-k", "--arg-for-wrapper") args = parser.parse_args() process = Popen(['wrapped_program', dpass_1, getattr(args, pass_1)], ...) 

another variant:

 parser = argparse.ArgumentParser() pass_action = parser.add_argument("-p", '--pass-me-on', help="Pass me on") parser.add_argument("-k", "--arg-for-wrapper") args = parser.parse_args() 

If you print pass_action (in a shell), you will get something like:

  _StoreAction(option_strings=['-p', '--pass-me-on'], dest='pass_me_on', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None) 

So, you can pull --name and dest from this object in this way:

 process = Popen(['wrapped_program', pass_action.option_strings[-1], getattr(args, pass_action.dest), ...], ...) 

You need to look at sys.argv to find out which option_string option is used (long, short or different). The parser writes nothing.

Note '--pass-me-on' produced by dest='pass_me_on' . Converting - to _ can complicate the output of one line from another.

If you have a dest string, you must use getattr to get it out of the args namespace or use vars(args)[dest] (access to the dictionary).

Another problem. If --patten has a list of arguments nargs='+', its value will be a list, as opposed to a string. You'd have to careful when merging that into the nargs='+', its value will be a list, as opposed to a string. You'd have to careful when merging that into the popen`.

+1
source

There seems to be no easy way to get the source parameter strings from the result of parser.parse_args() , but you can get them from the parser object. You just need to look into its __dict__ to get the parser settings after creating it. In your case, you want the _option_string_actions field. Unfortunately, this is not officially supported, since I could not find the ArgumentParser method dedicated to this, therefore YMMV. On Python 3:

Demo:

 parser = argparse.ArgumentParser() parser.add_argument('--foo', '-f', type=int, default=1000, help='intensity of bar') parser.add_argument('--bar', '-b', type=str, default='bla', help='whatever') store_action_dict=vars(parser)['_option_string_actions'] print(store_action_dict.keys()) # dict_keys(['--help', '-b', '-f', '-h', '--foo', '--bar']) 
0
source

Source: https://habr.com/ru/post/988635/


All Articles