Anji
Anji

Reputation: 723

Better way of programming

Im trying to write a script using python language(abc.py). I need to take few command line arguments while executing the script.

say -m, -p are my arguments. I need to have a string beside these options. ex:

 1. $> python abc.py -m 'first' -p 'second' {correct}
 2. $> python abc.py -p 'first' -m 'second' {correct}
 3. $> python abc.py -m -p 'first' 'second' {Incorrect}
 4. $> python abc.py 'first' -p 'second' {Incorrect}

I have more such arguments like -m, -p. What is the best algorithm to check if the passed arguments are in the correct format. I am unable think other than the method maintaining the previous argument and check based on it.

Thanks for you help in advance

Anji

Upvotes: 1

Views: 129

Answers (3)

dstromberg
dstromberg

Reputation: 7187

The modules are good, though they don't play nice with pylint, so I tend to do my own argument parsing to get better error detection. EG:

red = False
blue = False
green = False
red_weight = 1.0
green_weight = 1.0
blue_weight = 1.0

while sys.argv[1:]:
   if sys.argv[1] in [ '-h', '--help' ]:
      usage(0)
   elif sys.argv[1] in [ '-r', '--red' ]:
      red = True
   elif sys.argv[1] in [ '-b', '--blue' ]:
      blue = True
   elif sys.argv[1] in [ '-g', '--green' ]:
      green = True
   elif sys.argv[1] == '--red-weight':
      red_weight = float(sys.argv[2])
      del sys.argv[1]
   elif sys.argv[1] == '--green-weight':
      green_weight = float(sys.argv[2])
      del sys.argv[1]
   elif sys.argv[1] == '--blue-weight':
      blue_weight = float(sys.argv[2])
      del sys.argv[1]
   else:
      sys.stderr.write('%s: unrecognized option: %s\n' % (sys.argv[0], sys.argv[1]))
      usage(1)
   del sys.argv[1]

HTH

Upvotes: 0

Thorn
Thorn

Reputation: 340

You don't need to do that yourself, Python as they say comes with batteries included. The standard library has two modules for parsing command line arguments: argparse for python 2.7+ and optparse for 2.6 or older. Documentation for those has good usage examples, too.

Upvotes: 7

arhimmel
arhimmel

Reputation: 81

use the argparse module http://docs.python.org/library/argparse.html#module-argparse

Upvotes: 1

Related Questions