python - Use argparse to parse a list of objects -


i have program function takes class initializer , list of objects. each object consists of 3 variables id, value, , tag.

class package():      def __init__(self, id, value, name):         if (value <= 0):             raise valueerror("amount must greater 0")         self.id = id         self.value = value         self.tag = tag    class purchase():      def submit(some_list):         //do stuff  def main():     //help here!     parser = argparse.argumentparser()     parser.add_argument("id", help="id")     parser.add_argument("value", help="value")     parser.add_argument("tag", help="tag")     args = parser.parse_args()     some_list = [args.id, args.value, args.tag]     submit(some_list) 

i'm trying implement argparse in main() can run program doing like: python foo.py "int0 [(int1, float1, int2), (int3, float2, int4) ....]". number of objects in list variable , depends on user input.

initializer = num0  //first package object package.id = num1 package.value = num2 package.tag = num3  //second package object package.id = num4 package.value = num5 package.tag = num6   

you can make custom argument type , use ast.literal_eval() parse value.

working sample:

import argparse ast import literal_eval   class package():     def __init__(self, id, value, tag):         if (value <= 0):             raise valueerror("amount must greater 0")         self.id = id         self.value = value         self.tag = tag   def packages(s):     try:         data = literal_eval(s)     except:  # todo: avoid bare except , handle more specific errors         raise argparse.argumenttypeerror("invalid 'packages' format.")      return [package(*item) item in data]   parser = argparse.argumentparser() parser.add_argument('--packages', dest="packages", type=packages, nargs=1) args = parser.parse_args() print(args.packages) 

now if run script, list of package class instances printed:

$ python test.py --packages="[(1, 1.02, 3), (40, 2.32, 11)]" [[<__main__.package instance @ 0x10a20d368>, <__main__.package instance @ 0x10a20d4d0>]] 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -