python - Argparse, handle repeatable set of items -


Is it possible to create a set of related alternative arguments that related and repetitive?

Let's say I have three arguments - A, -B, -C that sets a set, -a required, but -b and -c are optional (updated)

I have the ability to specify many of these sets.

  Script.py -a 1 -b 2 -c3-A4-C6-A7-B8-A10   

Thus Will be defined as a list of

  [["a": 1, "b": 2, "c": 3}, {"a": 4, "c" : 6}, {"A": 7, "B": 8}, {"A": 10}]    

One way to repeat the argument is to use an 'append' verb type:

  import argparse parser = argparse.ArgumentParser () parser.add_argument (' Parser.add_argument ('- c', action = 'append') argv = '-a 1-B2-2', 'parser.add_argument' ('-', 'action' = 'append' C3-A4-C6-A7-B8-A10 'Argos = Parser. Parsa_arag (RGR) .split () print creates args   

:

  namespace (a = ['1', '4', ' 7 ',' 10 'Unfortunately, it loses some information, B = [' 2 ',' 8 '], c = [' 3 ',' 6 '])   

There is no way to associate '4' with '6' rather than '8'.

If you use '-' to isolate blocks of logic, then this running parser can work:

  parser = argparse.ArgumentParser () # SUPPRESS Namespace does not contain any of the namespace.ad_registration ('- a', type = int, default = argparse.SUPPRESS, required = true) Parser.add_argument ('- b', type = int, default = argparse .SUPPRESS) parser.add_argument ('- c', type = int, default = argparse.SUPPRESS) argv = '-a 1 -b 2 -c3-A4-C6 - -7-B8--10Eglist = [] Rest = argv.split () while remaining: RGS, rest = parser.parse_name_argain (rest) rest = rest [1:] remove # 1 - Print argist arglist.append (wars (args)) print arglist   

output:

  namespace (a name = 1, b = 2, c = Namespace (A = 4, C = 6) Namespace (A = 7, B = 8) Namespace (A = 10) [{'a': 1, 'c': 3, 'A': 10}] < / code>  Pre> 

I'm not sure that it is strong enough. I have made -a , so deleting it from one group will cause an error.


or Optimize the remote Iterator:

  set and val == start: set the set set = [val] and: set.append (val) yield Set argv = '-a 1 - def by_sets (iterator, start): set = [] B2-C3-A4-C6-A7-B8-A10' # Print List (By-Asset (ARG) Split (, '-a')) # [['A', '1', '-K', '3'], ['-A', '4 ',' -C ',' 6 '] , ... ['a', '', '-b', '2', '10']] arglist = [] for aset in bysets (argv.split (), '-a'): arglist. printed arglist   

output:

  [{'a': 1, 'c': 3) , 'b': 2}, {'a': 4, 'c': 6}, {'a': 7, 'b': 8}, {'a': 10}]   

Loop also has an understanding Can be written in the form:

  [for assets (for parser. Parse_arge) in assets (ARG split (), '-a']]    

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -