2

I have a question regarding passing arguments in Python.for Ex: in the script i am expecting arguments like

1.python run.py -create vairbale1 -reference variable2 many more variables
2.python run.py  -get -list variable many more variable

How can i enfore this in the script using optparse or getopt and if the arguments are invalid The i need to print Invalid arguments

 from optparse import OptionParser

 parser = OptionParser()
1

2 Answers 2

3

here's a snippet I've used. I worked for me, though you might have to change the parameter types.

parser = OptionParser()
parser.add_option('-n', '--db_name', help='DB Name (comma separated if multiple DBs - no spaces)')
parser.add_option('-H', '--db_host', help='DB host (comma separated if multiple DBs - no spaces)')
parser.add_option('-p', '--db_port', help='DB port (optional)')
parser.add_option('-u', '--db_user', help='DB user')
parser.add_option('-w', '--db_pass', help='DB password')
parser.add_option('-o', '--output-file', help='output file')

options, args = parser.parse_args()

errors = []
error_msg = 'No %s specified. Use option %s'
if not options.db_name:
    errors.append(error_msg % ('database name', '-n'))
if not options.db_host:
    errors.append(error_msg % ('database host', '-H'))
if not options.db_user:
    errors.append(error_msg % ('database user', '-u'))
if not options.db_pass:
    errors.append(error_msg % ('database password', '-w'))
if not options.output_file:
    errors.append(error_msg % ('output file', '-o'))

if errors:
    print '\n'.join(errors)
    sys.exit(1)
Sign up to request clarification or add additional context in comments.

5 Comments

Canu please explain for any one example how are you trying to use it
You run the script python blah.py -n dbname - H dbhost -p 8080 -u dbuser -w dbpass -o path_to_file then in the code you can access the values passed using options.db_name for example
K.Along with -n dbname if i have to pass one more parameter. How can i change it in the code? parser.add_option('-n', '--db_name','var1', help='DB Name (comma separated if multiple DBs......)
The extra variables will be in the args variable after you call parser.parse_args()
thanks. This got me going well... I just wanted to mention that you can easily print the help info provided with parser.format_help().strip() then exit with sys.exit(0) to match the native function.
2

You can use custom action to validate your data like

import argparse
import re

class ValidateEmailAction(argparse.Action):
    ''' 
    Function will not validate domain names.
    e.g. [email protected] is valid here.
    '''
    def __call__(self, parser, namespace, values, option_string=None):

        super(argparse.Action, self).__call__(parser, namespace, values,
                                                  option_string=option_string)
        email = values
        pattern = "^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$"
        if not re.match(pattern, email) != None:
            raise AttributeError


parser = argparse.ArgumentParser()
parser.add_argument('-e', '--email', action=ValidateEmailAction, help='Enter valid email.')

Also check the custom action on http://docs.python.org/dev/library/argparse.html#action

2 Comments

your code is throwing error even if i enter correct email address: super(argparse.Action, self).__call__(parser, namespace, values, AttributeError: 'super' object has no attribute '__call__'
This might be new change. I will update you after checking new changes in argparse.Action

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.