Python Command Line Arguments

Python provides the ability to use Python applications and scripts via the command-line interface. Command line arguments can be read by using different methods or modules like sys.argv , getopt module or argparse module. In this tutorial, we examine different use cases for the Python command-line arguments.

Using sys.argv

The sys module provides the argv submodule in order to read arguments provided to the Python script or application. This module provides the provided arguments as a list and also the number of arguments that can be returned with the len() function. Also, the sys.argv[0] provides the Python script file name by default. This means the provided arguments are listed with sys.argv[1] and next items.

#!/bin/python3

import sys

argument_count = len(sys.argv)

script_name = sys.argv[0]

for a in range(1,argument_count):
   print(sys.argv[a],end=" ")

Using getopt Module

The getopt module is very similar to the C programming language getopt() function. The getopt module provides more advanced usage by separating the input string by parameter validation. The getops can be used to create short and long options and validate them properly.

#!/bin/python3

import getopt, sys

argument_list = sys.argv[1:]

options = "hns:"

long_options = ["Name","Surname","Help"]

arguments, values = getopt.getopt(argument_list, options, long_options)
    
for currentArgument, currentValue in arguments:
   if currentArgument in ("-h", "--Help"):
      print("Displaying Help")
          
   elif currentArgument in ("-n", "--Name"):
      print("Displaying Name", sys.argv[1])
   elif currentArgument in ("-s", "--Surname"):
      print("Displaying Surname", sys.argv[2])

Using argparse Module

The argparse module is superior to previously described methods like sys.argv and getops . The argparse provides positional arguments, the default value for arguments, help message, specifying data type of argument, etc.

#!/bin/python3

import argparse

parser = argparse.ArgumentParser()

parser.add_argument("-n","--Name",help="Name information")

parser.add_argument("-s","--Surname",help="Surname information")

arguments = parser.parse_args()

print(arguments)

Leave a Comment