2

I am trying to get three arguments from command line:

-o (for outputfile) -k (number of clusters) -l (data to be clustered)

So i wrote this.

def get_input():
print 'ARGV :', sys.argv[1:]
options, remainder = getopt.getopt(sys.argv[1:], 'o:v:k:l', ['output=', 
 'verbose',
 'k_clust=',
 'limit='])
print "options ",options
file_flag , k_flag, count_flag = False, False,False
for opt, arg in options:
 print opt
 if opt in ('-o', '--output'):
 print "here ", opt, arg
 output_filename = arg
 o_flag = True
 if opt in ('-v', '--verbose'):
 verbose = True
 if opt == '--version':
 version = arg
 if opt in ('-k','--k_clust'):
 print "here", opt, arg
 k_clust = arg
 k_flag = True
 if opt in ('-l','--limit'):
 kcount = arg
 assert kcount!=0 and kcount!= ''
 print "limit ", arg
 count_flag = True
if k_flag == False:
 sys.exit(" no cluster specified, will be exiting now")
if o_flag == False:
 print "using default outfile name ",output_filename
if count_flag == False:
 kcount = 10000000
return output_filename, k_clust,kcount

Everything is working on fine except the -l flag so if my command line command is this:

$python foo.py -o foo.txt -k 2 -l 2

and the print argv prints

ARGV : ['-o', 'demo.txt', '-k', '2', '-l', '2']

but the options is:

options [('-o', 'demo.txt'), ('-k', '2'), ('-l', '')]

Notice that nothing is being parsed in the "l" field. Wat am i doing wrong? Thanks

asked Jan 27, 2012 at 20:00

2 Answers 2

9

getopt is a rather old module. If you have Python2.7, use argparse. If you have a slightly older version of Python>= 2.3, you can still install argparse:

With

import argparse
parser=argparse.ArgumentParser()
parser.add_argument('-o', help = 'outputfile')
parser.add_argument('-k', help = 'number of clusters')
parser.add_argument('-l', help = 'data to be clustered')
args=parser.parse_args()
print(args)

running

test.py -o foo.txt -k 2 -l 2

yields

Namespace(k='2', l='2', o='foo.txt')
answered Jan 27, 2012 at 20:04
Sign up to request clarification or add additional context in comments.

Comments

4

It's because in your shortopts parameter: 'o:v:k:l', the "l" needs to be followed by a colon ":"

Since it's not, the "2" is being put into the remainder variable.

answered Jan 27, 2012 at 20:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.