1

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

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

2.6 and older can install by easy_install argparse as well :)
thanks for throwing light on me. SO will never disappoint me :)
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.