Problem: Need to parse some specific arguments which could be in any order, non are optional: -h -d -src -dst
Am new to Python and have looked at the alternatives such as getopt and argparse but couldn’t get a working example so went custom as below;
argv=sys.argv[1:]
args=[]
for idx, arg in enumerate(argv):
# if is arg
if arg.startswith("-"):
# find arg match
for i in ("-h","-d:","-src:","-dst:"):
# requires var
if i == arg + ':' and idx < len(argv)-1:
if not argv[idx+1].startswith("-"):
args.append((arg,argv[idx+1]))
break
# no var
elif i == arg:
args.append((arg,""))
break
else:
continue
# may contain duplicates
print(args)
# no dupes
print(set(args))
Can anyone suggest improvements and/or better examples to achieve the problem objective?
in python 2.6 there is a module called optparse
which does what you want.
example from the docs:
another example: