Search code examples
pythongetopt

Python command line arg with getopt does not work


I modified the sample code given here: sample code for getopt

as follows, but it does not work. I am not sure what I am missing. I added a "-j" option to this existing code. Eventually, I want to add as many as required command option to meet my needs.

When I give input as below, it does not print anything.

./pyopts.py -i dfdf -j qwqwqw -o ddfdf
Input file is " 
J file is " 
Output file is " 

Can you please let me know whats wrong here?

#!/usr/bin/python

import sys, getopt

def usage():
    print 'test.py -i <inputfile> -j <jfile> -o <outputfile>'

def main(argv):
   inputfile = ''
   jfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hij:o:",["ifile=","jfile=","ofile="])
   except getopt.GetoptError:
      usage()
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         usage()
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg 
      elif opt in ("-j", "--jfile"):
         jfile = arg 
      elif opt in ("-o", "--ofile"):
         outputfile = arg 

   print 'Input file is "', inputfile
   print 'J file is "', jfile
   print 'Output file is "', outputfile

if __name__ == "__main__":
   main(sys.argv[1:])

Solution

  • Your error is omitting a colon following the i option. As stated by the link you supplied:

    options that require an argument should be followed by a colon (:).

    Therefore, the corrected version of your program should contain the following:

       try:
          opts, args = getopt.getopt(argv,"hi:j:o:",["ifile=","jfile=","ofile="])
       except getopt.GetoptError:
          usage()
          sys.exit(2)
    

    Executing it with the specified arguments derives the expected output:

    ~/tmp/so$ ./pyopts.py -i dfdf -j qwqwqw -o ddfdf
    Input file is " dfdf
    J file is " qwqwqw
    Output file is " ddfdf
    

    However, as a comment to your question specifies, you should use argparse rather than getopt:

    Note: The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. Users who are unfamiliar with the C getopt() function or who would like to write less code and get better help and error messages should consider using the argparse module instead.