Easy Tutorial
❮ Python Xml Processing Python Operator ❯

Python3 Command Line Arguments

Python3 Basic Syntax

Python provides the getopt module to retrieve command line arguments.

$ python test.py arg1 arg2 arg3

Python can also use sys's sys.argv to retrieve command line arguments:

-

sys.argv is a list of command line arguments.

-

len(sys.argv) calculates the number of command line arguments.

Note: sys.argv[0] represents the script name.

Example

The code for the test.py file is as follows:

Example

#!/usr/bin/python3

import sys

print('Number of arguments:', len(sys.argv), 'arguments.')
print('Argument list:', str(sys.argv))
print('Script name:', str(sys.argv[0]))

Executing the above code, the output is:

$ python3 test.py arg1 arg2 arg3
Number of arguments: 4 arguments.
Argument list: ['test.py', 'arg1', 'arg2', 'arg3']
Script name: test.py

getopt Module

The getopt module is a module specifically designed for handling command line arguments, used to retrieve command line options and parameters, which are sys.argv. Command line options make the program's parameters more flexible. It supports short option mode - and long option mode --.

This module provides two methods and an exception for parsing command line arguments.

getopt.getopt Method

The getopt.getopt method is used to parse the command line argument list, with the following syntax:

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

Method parameter description:

-

args: The list of command line arguments to be parsed.

-

options: Defined in string format, a colon : following options indicates that the option must have an additional parameter, without a colon indicates that the option does not have additional parameters.

-

longoptions: Defined in list format, an equals sign = following longoptions indicates that if this option is set, it must have an additional parameter, otherwise it does not have additional parameters.

The return value of this method consists of two elements: the first is a list of (option, value) tuples. The second is a list of parameters that do not have - or --.

Next, we define a site() function, and then input the site name name and URL url via the command line, using the abbreviations n and u:

Example

import sys 
import getopt 
  
def site(): 
    name = None
    url = None
  
    argv = sys.argv[1:] 
  
    try: 
        opts, args = getopt.getopt(argv, "n:u:")  # Short option mode
      
    except: 
        print("Error") 
  
    for opt, arg in opts: 
        if opt in ['-n']: 
            name = arg 
        elif opt in ['-u']: 
            url = arg 
      
    print(name + " " + url) 
  
site()

Testing the above code, input in the command line:

python3 test.py -n tutorialpro -u www.tutorialpro.org

The output is:

tutorialpro www.tutorialpro.org

The following example demonstrates the use of long option mode:

Example

import sys 
import getopt 
  
def site(): 
    name = None
    url = None
  
    argv = sys.argv[1:] 
  
    try: 
        opts, args = getopt.getopt(argv, "n:u:",  
                                   ["name=", 
                                    "url="])  # Long option mode
      
    except: 
        print("Error") 
  
    for opt, arg in opts: 
        if opt in ['-n', '--name']: 
            name = arg 
        elif opt in ['-u', '--url']: 
            url = arg 
      
    print(name + " " + url) 
  
site()

This is a Chinese to English translation, please provide the English translation for this text. Do not provide any explanations or text apart from the translation.

Chinese:

elif opt in ['-u', '--url']:
    url = arg

print(name + " " + url)

site()

Test the above code by entering the following in the command line:

python3 test.py -n tutorialpro -u www.tutorialpro.org

The output will be:

tutorialpro www.tutorialpro.org

Another method is getopt.gnu_getopt, which is used less frequently and will not be discussed further here.


Exception getopt.GetoptError

This exception is triggered when no arguments are found or the required parameter for an option is missing.

The exception argument is a string indicating the reason for the error. The attributes msg and opt provide error information related to the option.

Example

Suppose we create a script that can pass two filenames to the script file via the command line, and we also have an option to view the script usage. The script usage is as follows:

usage: test.py -i <inputfile> -o <outputfile>

The test.py file code is as follows:

Example

#!/usr/bin/python3

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 <inputfile> -o <outputfile>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print ('test.py -i <inputfile> -o <outputfile>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
    print ('Input file:', inputfile)
    print ('Output file:', outputfile)

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

Executing the above code will produce the following output:

$ python3 test.py -h
usage: test.py -i <inputfile> -o <outputfile>

$ python3 test.py -i inputfile -o outputfile
Input file: inputfile
Output file: outputfile

Python3 Basic Syntax

❮ Python Xml Processing Python Operator ❯