Comma separated inputs instead of space separated inputs for argparse

前端 未结 5 971
灰色年华
灰色年华 2021-01-19 02:30

I\'m using argparse to receive inputs from the command line to run my script.

My current input string looks like this:

path> python &         


        
5条回答
  •  遥遥无期
    2021-01-19 03:18

    Here this comma-separated input is actually a different type. All you have to is to define the type. Here I define a custom type that does it.

    class DelimiterSeperatedInput:
      def __init__(self, item_type, separator=','):
        self.item_type = item_type
        self.separator = separator
    
      def __call__(self, value):
        values = []
        try:
          for val in value.split(self.separator):
             typed_value = self.item_type(val)
             values.append(typed_value)
        except Exception:
          raise ArgumentError("%s is not a valid argument" % value)
        return values
    
    parser.add_argument('-t', type=DelimiterSeperatedInput(str),
                        help='comma separated string values')
    parser.add_argument('-f', type=DelimiterSeperatedInput(float, ":"), 
                        help="colon separated floats')
    

    This code may not work as-is, you might have to fix. But it was to give an idea.

    Note: I could reduce the __call__ function body by using list, map etc. But then it wouldn't be very readable. Once you get the idea, you can do kinds of stuff with it.

提交回复
热议问题