Register Login

What are Command-line arguments in Python?

Creating a text-based program where putting input or values through commands sometimes become essential for programmers. Such type of program needs an external data feeding concept that can be framed from the programming point.

That is where Python's command-line argument comes in. In this article, you will learn about the command-line argument and its working in Python.

What is Command-line argument?

The command-line argument is a technique and concept provided by the programming language to cater to arguments that are given after the program name in the command-line shell.

The values provided by the user at the time of program execution in the command-line shell helps in modifying the behavior of a program.
Almost all modern programming language supports the concept of command-line argument. There are three different ways we can implement the concept of command-line argument in Python. These are:

  • Using the sys module
  • Using the getopt module
  • Using the argparse module

Before digging into the practical aspect of the command-line argument, let us first understand the real-life or practical applications of this.

What is the purpose of introducing command-line argument?

We are all familiar with the concept of a command-line interface (CLI) application. These applications directly take commands or values as input and work upon them to give the desired result.

When programmers and developers need to create applications that should work on the principle of command-line or text-based commands & values, those programs need the concept of command-line argument.

Most of the shell programs that we have in Linux (bash, csh, etc.) and Windows (Powershell) use this concept from the developers' perspective. So, if you are planning to create such applications that will be driven entirely by commands, values, texts, or strings, command-line argument programs are the only solutions.

Working with Python Command-line:

Method 1: Using the sys module:

The sys module helps in providing functions and variables that can handle and manage various components of the runtime environment in Python. It can access some variables owned by the interpreter and allow to use of external operations belonging to the system.

Among its variables, the sys.argv is one that creates a list structure of all the values fed to the program at runtime.

  • It renders a list of all command line arguments fed at the time of program run.
  • sys.argv[0] is one of the important variable (the first amongst all) name of the first/current element in that Python script.
  • len(sys.argv) fetches the number of command line arguments available when the script runs.

Program:

import sys
numb = len(sys.argv)
print(" Counting one by one all arguments passed:", numb - 1)
print("\n Name of this Python script is :", sys.argv[0])
print("\n All the arguments passed are:", end = " ")
for i in range(1, numb):
    print(sys.argv[i], end = " ")
    
mul = 1
for i in range(1, numb):
    mul *= int(sys.argv[i])
print("\n\n The multiplicative value of all the arugments are :", mul)

Output:



Explanation:

First we will import sys module. Then we will use len(sys.argv) method to check the number of arguments the sys.argv is having or given by the user. After counting all the arguments passed, we will also print the name of the python script.

Next, we will use the for loop to display all the arguments passed through the command-line argument method. Next, we have created a variable mul and assigned it with a value 1. Then we have initiated a for loop that will run till numb.

Then we will fetch the arguments one by one using the sys.argv[i] and use the shorthand operator to multiply and store it in the variable ‘mul’. Finally, we use another print() function that will display the ultimate multiplication value of all the arguments passed through the command-line technique.

Method 2: Using the getopt module:

The second technique to use the command-line argument in Python is using the getopt module. It works alike to that of C programming's getopt() function.

Unlike the sys module, the getopt module will extend the separation of the input string with some additional command attributes or parameter validation.

It is beneficial when allowing both short, and long options to be included as a value in the command line. However, this module entails the employment of the sys module to process input data accurately.

Program:

import sys
import getopt
def empName():
    f_name = None
    l_name = None
    argv = sys.argv[1:]
  
    try:
        opts, args = getopt.getopt(argv, "f:l:")
    except:
        print("Invalid Input....")
    for opt, arg in opts:
        if opt in ['-f']:
            f_name = arg
        elif opt in ['-l']:
            l_name = arg
    print( f_name," ", l_name)
  
empName()

Output:

Explanation:

First we will import sys module followed by the getopt module. Then we will create a user-defined function empName() and initialize f_name and l_name as None and argv as sys.argv[1:].

Then within the try block of the exception handling, we will assign two variables opts, args = getopt.getopt(argv, "f:l:") with the arguments passed through command-line within the getopt.getopt() method. Under the eccept block, we will use the print() function to display "Invalid Input...." in case the arguments are not valid.

Then, we will create the attributes and their meaning using the if statements along with the attribute value prefixed with a dash (-). Finally, we will display the two values that will be passed along with attributes as strings.

Method 3: Using the argparse module:

Another exciting way of creating programs and apps that will take command-line arguments within a Python program is through argparse module and its ArgumentParser() method.

With the help of argparse module and its built-in methods, there is a better possibility to provide a set of options as it affords a lot of choices to put within its method such as the default value for arguments, positional arguments, help info, etc.

Program:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--Output", help = "Show Output")
args = parser.parse_args()
if args.Output:
    print("Your favourite color is : % s" % args.Output)

Output:

Explanation:

First we will import argparse module. Then we will create a variable and assign the argparse.ArgumentParser() value that will fetch the arguments from the user.

Then, we will add an argument or attribute that we have to provide in the command line to represent the output.
We can use -o or –Output both as the attribute to make the program understand that the user wants to display the output. The help parameter also accepts string that users can use in order to understand the "-o", "--Output" meaning.

Finally the parser.parse_args() will parse the meaning of the attributes and the value (passed as argument). Finally, the if statement checks if the output exists, the print() function will display the favorite color along with the string passed.

Conclusion:

All these three modules are way more powerful to perform command-line operations. But the first and third techniques are simple and require importing one module to import.

That makes the program lightweight and efficient. The second method requires both the sys and the getopt modules. But the second option also provides additional attributes to be added while passing the command-line input into the program.

But again, it is better to use the third technique (argparse module) if your program requires a lot of options or attributes to be added in the input. The third one renders the maximum efficiency yet allows programmers to put various operations through its parameters.