Python argparse with nargs behaviour incorrect

前端 未结 2 786
傲寒
傲寒 2021-01-15 11:55

Here is my argparse sample say sample.py

import argparse
parser = argparse.ArgumentParser()
parser.add_argument(\"-p\", nargs=\"+\", help=\"Stuff\")
args = p         


        
2条回答
  •  一个人的身影
    2021-01-15 12:51

    Note: python 3.8 adds an action="extend" which will create the desired list of ['x','y']

    To produce a list of ['x','y'] use action='append'. Actually it gives

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

    For each -p it gives a list ['x'] as dictated by nargs='+', but append means, add that value to what the Namespace already has. The default action just sets the value, e.g. NS['p']=['x']. I'd suggest reviewing the action paragraph in the docs.

    optionals allow repeated use by design. It enables actions like append and count. Usually users don't expect to use them repeatedly, or are happy with the last value. positionals (without the -flag) cannot be repeated (except as allowed by nargs).

    How to add optional or once arguments? has some suggestions on how to create a 'no repeats' argument. One is to create a custom action class.

提交回复
热议问题