C-style parser for command line options in Python


Python’s sys module provides access to any command-line arguments via the sys.argv. sys.argv is the list of command-line arguments and sys.argv[0] is the program ie. the script name.

Save following code as args.py

import sys
print ('argument list', sys.argv)

Execute above script from command line as follows:

C:\python37>python args.py 11 22
argument list ['args.py', '11', '22']

The getopt module has funcions toparse the command line arguments in sys.argv. It supports the same conventions as the Unix getopt() function (including the special meanings of arguments of the form ‘-‘ and ‘--‘).

API is designed to be familiar to users of the C getopt() function.

getopt(args, shortopts, longopts=[])

Parses command line options and parameter list. args is the argument list excluding sys.argv[0], which is the leading reference to the running program. Typically, this means sys.argv[1:]. Arguments to this function are as follows −

shortopts: is the string of option letters that will be recognized by the script. Options that require an argument are followed by a colon (':'; i.e., the same format that Unix getopt() uses).

Longopts: if specified, must be a list of strings with the names of the long options which should be supported. The leading '--' characters should not be included in the option name. Long options which require an argument should be followed by an equal sign ('=').

The return value consists of two elements: the first is a list of (option, value) pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of args). Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.g., '-x') or two hyphens for long options (e.g., '--long-option'), and the option argument as its second element, or an empty string if the option has no argument. The options occur in the list in the same order in which they were found, thus allowing multiple occurrences. Long and short options may be mixed.

GetoptError is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none.

Example

import sys, getopt

args=sys.argv[1:]
inputfile = ''
outputfile = ''
try:
   opts, args = getopt.getopt(args,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
   print ('test.py -i <inputfile> -o <outputfile>')
   sys.exit(2)
for opt, arg in opts:
   if opt == '-h':
      print ('args.py -i <inputfile> -o <outputfile>')
      sys.exit()
   elif opt in ("-i", "--ifile"):
      inputfile = arg
   elif opt in ("-o", "--ofile"):
      outputfile = arg
print ('Input file is "', inputfile)
print ('Output file is "', outputfile)

Output

C:\python37>python args.py -h
args.py -i <inputfile> -o <outputfile>
C:\python37>python args.py -i abc.txt -o xyz.txt
Input file is " abc.txt
Output file is " xyz.txt
C:\python37>python args.py --ifile=abc.txt --ofile=xyz.txt
Input file is " abc.txt
Output file is " xyz.txt
raja
Published on 08-May-2019 16:54:55
Advertisements