I have the following Python code that has 1 command line optional parameter (c
) that has an argument and 2 options (a
and b
) that do not have an argument:
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"abc:",["csvfile="])
except getopt.GetoptError:
print 'Error in usage - a does not require an argument'
sys.exit(2)
for opt, arg in opts:
print "Raw input is: {}" .format(opt)
if opt in ("-c", "--csvfile"):
outputfile = arg
print 'Output file is {}' .format(outputfile)
elif opt == '-a':
print 'Alpha'
elif opt == '-b':
print 'Beta'
print 'User choice is {}' .format(opt.lstrip('-'))
if __name__ == "__main__":
main(sys.argv[1:])
When I enter python readwritestore.py -a
I get:
Raw input is: -a
Alpha
User choice is a
This is what I was hoping for if the commandline argument is -a
. However, if I enter python readwritestore.py -a csvfile_name
, then I get:
Raw input is: -a
Alpha
User choice is a
This is not what I intended for. In this function, c
is the only option that rquires an argument. If I enter a
with an argument,
the code should give the error message that I set up
Error in usage - a does not require an argument
This does not happen for a
or b
. It is allowing the argument to be entered without raising an error.
If the options that do not require an argument are entered with an argument, then I would like it to raise an error. python readwritestore.py -a text
and python readwritestore.py -b text
should raise the error Error in usage - a does not require an argument
.
Is there a way to specify this? Is getopt()
the correct way to do this?
Additional Information:
I only want python readwritestore.py -c text
to work with the argument. For the other 2 options, a
and b
, the code should raise the error.