Python script sys argv

Python — Command Line Arguments

Python Command Line Arguments provides a convenient way to accept some information at the command line while running the program. The arguments that are given after the name of the Python script are known as Command Line Arguments and they are used to pass some information to the program. For example —

$ python script.py arg1 arg2 arg3

Here Python script name is script.py and rest of the three arguments — arg1 arg2 arg3 are command line arguments for the program. There are following three Python modules which are helpful in parsing and managing the command line arguments:

sys module — System-specific parameters

The Python sys module provides access to any command-line arguments via the sys.argv. This serves two purposes −

  • sys.argv is the list of command-line arguments.
  • len(sys.argv) is the number of command-line arguments.

Here sys.argv[0] is the program ie. script name.

Example

Consider the following script test.py −

import sys print 'Number of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv)

Now run above script as below. All the programs in this tutorial need to be run from the command line, so we are unable to provide online compile & run option for these programs. Kindly try to run these programs at your computer.

$ python test.py arg1 arg2 arg3

This produce following result −

Number of arguments: 4 arguments. Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

As mentioned above, first argument is always script name and it is also being counted in number of arguments.

Parsing Command-Line Arguments

Python provided a getopt module that helps you parse command-line options and arguments. This module provides two functions and an exception to enable command line argument parsing.

getopt.getopt method

This method parses command line options and parameter list. Following is simple syntax for this method −

getopt.getopt(args, options, [long_options])

Here is the detail of the parameters −

  • args − This is the argument list to be parsed.
  • options − This is the string of option letters that the script wants to recognize, with options that require an argument should be followed by a colon (:).
  • long_options − This is optional parameter and if specified, must be a list of strings with the names of the long options, which should be supported. Long options, which require an argument should be followed by an equal sign (‘=’). To accept only long options, options should be an empty string.

This method getopt.getopt() returns value consisting 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. 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’).

Example

Following is a Python program which takes three arguments at command line:

  1. First command line argument is -h which will be used to display the usage help of the program.
  2. Second argument is either -i or —ifile which we are considering as input file.
  3. Third argument is either -o or —ofile which we are considering as output file.

Here is the following script to test.py −

import sys, getopt def main(argv): inputfile = '' outputfile = '' opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) for opt, arg in opts: if opt == '-h': print ('test.py -i -o ') 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) if __name__ == "__main__": main(sys.argv[1:])

Now, run above script as follows −

This will produce the following result:

Input file is IN Output file is OUT

We can also run the above program as follows:

$ python test.py --ifile IN --ofile OUT

This will produce the same result as in case of -i and -o:

Input file is IN Output file is OUT

We can use h option to check the usage of the program:

This will produce the following result:

Exception getopt.GetoptError

Consider we use some other option which has not been implemented in the program. This will raise an exception. For example, let’s try to run the same program with wrong option -p as follows:

This will raise an exception as below:

Traceback (most recent call last): File "test.py", line 21, in main(sys.argv[1:]) File "test.py", line 8, in main opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) File "/usr/lib64/python3.6/getopt.py", line 95, in getopt opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) File "/usr/lib64/python3.6/getopt.py", line 195, in do_shorts if short_has_arg(opt, shortopts): File "/usr/lib64/python3.6/getopt.py", line 211, in short_has_arg raise GetoptError(_('option -%s not recognized') % opt, opt) getopt.GetoptError: option -j not recognized

This exception is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none. The argument to the exception is a string indicating the cause of the error. The attributes msg and opt give the error message and related option.

Example

Following is a correct Python program which makes use of try. except block and capture getopt.GetoptError exception:

import sys, getopt def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print ('test.py -i -o ') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('test.py -i -o ') 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) if __name__ == "__main__": main(sys.argv[1:])

Now, run above script as follows −

This will run the program gracefully and will display the program usage as we have implemented in exception section:

Python argparse Module

Python argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages. The module will also issue errors when users give the program invalid arguments.

Example

Following is an example which makes simple use of argparse to accept a name parameter:<>/p>

import argparse argParser = argparse.ArgumentParser() argParser.add_argument("-n", "--name", help="your name") args = argParser.parse_args() print("args=%s" % args) print("args.name=%s" % args.name)

You can add as many arguments as you like using add_argument() method, infact you can also provide required data type of the argument as follows.

argParser.add_argument("-i", "--int", type=int, help="your numeric age ")

However, let’s try to run above program as follows:

This will display the following help:

usage: test.py [-h] [-n NAME] optional arguments: -h, --help show this help message and exit -n NAME, --name NAME your name

Now if we provide our name to the program as follows:

It will display following result:

args=Namespace(name='Zara') args.name=Zara

Источник

Читайте также:  All php mysql functions available
Оцените статью