Python argparse with nargs behaviour incorrect -


here argparse sample sample.py

import argparse parser = argparse.argumentparser() parser.add_argument("-p", nargs="+", help="stuff") args = parser.parse_args() print args 

python - 2.7.3

i expect user supplies list of arguments separated spaces after -p option. example, if run

$ sample.py -p x y  namespace(p=['x', 'y']) 

but problem when run

$ sample.py -p x -p y namespace(p=['y']) 

which neither here nor there. 1 of following

  • throw exception user asking him not use -p twice instead supply them 1 argument
  • just assume same option , produce list of ['x','y'].

i can see python 2.7 doing neither of them confuses me. can python 1 of 2 behaviours documented above?

to produce list of ['x','y'] use action='append'. gives

namespace(p=[['x'], ['y']]) 

for each -p gives list ['x'] dictated nargs='+', append means, add value namespace has. default action sets value, e.g. ns['p']=['x']. i'd suggest reviewing action paragraph in docs.

optionals allow repeated use design. enables actions append , count. users don't expect use them repeatedly, or happy last value. positionals (without -flag) cannot repeated (except allowed nargs).

how add optional or once arguments? has suggestions on how create 'no repeats' argument. 1 create custom action class.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -