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()
asked Mar 29, 2012 at 10:03
Rajeev
47.3k80 gold badges191 silver badges290 bronze badges
2 Answers 2
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)
answered Mar 29, 2012 at 10:14
Nostradamnit
8701 gold badge10 silver badges21 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Rajeev
Canu please explain for any one example how are you trying to use it
Nostradamnit
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
Rajeev
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......)
Nostradamnit
The extra variables will be in the args variable after you call parser.parse_args()
brandeded
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.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
answered Mar 29, 2012 at 10:58
NPatel
21.4k17 gold badges105 silver badges166 bronze badges
2 Comments
Ciasto piekarz
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__'NPatel
This might be new change. I will update you after checking new changes in
argparse.Actionlang-py
optparsemodule has been depreciated. As of 2.7 you'll probably want to use theargparsemodule: docs.python.org/library/argparse.html#module-argparse