Python argparse with nargs behaviour incorrect

前端 未结 2 772
傲寒
傲寒 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:26

    I ran into the same issue. I decided to go with the custom action route as suggested by mgilson.

    import argparse
    class ExtendAction(argparse.Action):
      def __call__(self, parser, namespace, values, option_string=None):
        if getattr(namespace, self.dest, None) is None:
          setattr(namespace, self.dest, [])
        getattr(namespace, self.dest).extend(values)
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", nargs="+", help="Stuff", action=ExtendAction)
    args = parser.parse_args()
    print args
    

    This results in

    $ ./sample.py -p x -p y -p z w
    Namespace(p=['x', 'y', 'z', 'w'])
    

    Still, it would have been much neater if there was an action='extend' option in the library by default.

提交回复
热议问题