Home Education Command Line Arguments In Python 
Command Line Arguments In Python

Command Line Arguments In Python 

by Samson

Command Line Parameters are the arguments that are presented after the program name in the operating system’s command-line shell. Python has several methods for dealing with these sorts of parameters. Python for beginners will have the three most common:

  • Using sys.argv
  • Using getopt module
  • Using argparse module

Handling Command Line Arguments in Python

Command-line arguments can be handled in a variety of ways in Python 3. The sys module is the default method. It is intimately related to the C library in terms of nomenclature and use (libc). The getopt module, which supports both short and long options, as well as parameter value evaluation, is the second choice. The argparse module is a descendant of the optparse module, which was accessible until Python 2.7.

Each of these options has advantages and disadvantages, so weigh them all to discover which best meets your needs.

  • The sys Module

This is a simple module that has been included with Python since its inception. It uses argc/argv to retrieve the arguments, which is fairly similar to the C library. The command-line arguments are implemented in the sys module as a simple list structure called sys.argv.

A single argument is represented by each list element. The name of the Python script, sys.argv[0], is the first item in the list. The command-line arguments 2 through n are represented by the list components sys.argv[1] to sys.argv[n]. A space is used as a delimiter between the parameters. To be read correctly by sys, argument values that contain a space must be wrapped by quotes.

The number of entries in the list is the equivalent of argc. Use the Python len() operator to get this number. Later on, we’ll use a code sample to demonstrate this.

The First CLI Argument is Printed

The script will identify how it was called in this initial case. This data is saved in the first command-line parameter, which is indexed with 0. The code below demonstrates how to find out what your Python script’s name is.

import sys

print (“The script has the name %s” % (sys.argv[0])

This code should be saved in a file called arguments-program-name.py and then called as shown below. The following is the output, which includes the file name as well as its entire path:

$ python arguments-program-name.py

The script has the name arguments-program-name.py

$ python /home/user/arguments-program-name.py

The script has the name /home/user/arguments-program-name.py

We obtain not just the name of the Python file, but also the whole path used to call it, as you can see from the second call above.

Counting the Number of Arguments

In this second example, we simply use the built-in len() function to count the amount of command line inputs. The list we need to look at is sys.argv. We deduct 1 from the number of parameters in the code below since one of those arguments (the first one) is usually set as the file name, which isn’t always beneficial to us. As a result, len(sys.argv) – 1 is the actual number of arguments given by the user.

import sys

# Count the arguments

arguments = len(sys.argv) – 1

print (“The script is called with %i arguments” % (arguments))

Save the file as arguments-count.py and give it a new name. Below are several examples of how to call this script. There are three different scenarios in this:

  • Without any further command-line options, a call is made.
  • Two arguments in a call
  • A call with two parameters, the second of which is a quoted string with a space in it.

$ python arguments-count.py

The script is called with 0 arguments

$ python arguments-count.py –help me

The script is called with 2 arguments

$ python arguments-count.py –option “long string”

The script is called with 2 arguments

Iterating Through Arguments

Except for the program name, our third example outputs every single parameter supplied to the Python script. As a result, we start with the second list entry and loop over the command line arguments. Remember that Python lists are 0-based, thus this is index 1.

import sys

# Count the arguments

arguments = len(sys.argv) – 1

# Output argument-wise

position = 1

while (arguments >= position):

    print (“Parameter %i: %s” % (position, sys.argv[position]))

    position = position + 1

Our code, which was saved to the file arguments-output.py, is called below. The output, like with our previous example, shows three separate calls:

  • A call made without any objections
  • Two arguments in a call
  • A call with two parameters, the second of which is a quoted string with a space in it.

$ python arguments-output.py

$ python arguments-output.py –help me

Parameter 1: –help

Parameter 2: me

$ python arguments-output.py –option “long string”

Parameter 1: –option

Parameter 2: long string

Remember that unless the parameter is wrapped by quotes, it is normally delimited by a space.

  • The getopt Module

The getopt module is the second way to implement command-line options in Python. For processing command-line arguments, the Python getopt module is analogous to the C getopt() method.

To make command-line parameter processing easier, the getopt module includes two methods and an exception.

getopt.getopt(args, Unix options, [long_options or gnu options])

args à arguments list to be parsed

unix options à  “ho:v”

gnu options à long options parameter à [“help”, “output=”, “verbose”]


# importing standard libraries

import getopt

import sys

# extracting command line arguments excluding file name

argv = sys.argv[1:] # parsing the argument list


opts, args = getopt.getopt(argv, ‘ho:v’)



except getopt.GetoptError:

print(‘Something went wrong!’)



C: lUsens thplAppData \Local \Programs\Python) Python37-32)py demo.py -o rajasthan -h jaipur udaipur alvar

I”rajasthan”), (“-h’1(‘jaipur”Iudaipur”,”alwar”]


Imported are standard libraries. The getopt module is used to parse command-line arguments while the sys module is used to get command-line arguments. By eliminating argv[0], i.e. the file name, we may extract parameters from argv. Using getopt.getopt to parse the arguments (). The arguments and their values are saved in two variables called opts and args.

  • The argparse Module

Using the argparse module is preferable to the other two methods since it offers more features such as positional arguments, default values for arguments, help messages, and defining the data type of an argument.

Note: that it contains -h, as well as its extended variant –help, as a default optional parameter.

Code :

import argparse

parser = argparse.ArgumentParser()

args = parser.parse_args()

Importing the first argparse module. Then an argparse object. The function ArgumentParser() is created.

When we run the above program on the command prompt without providing any input, nothing happens. However, when we use the optional help argument with input, we obtain the following result.


C: \Usersthpacd C:AusersthptAppData\Local \Programs\Python\Python37- 32

C: \users\hp \AppData\Local \Programs \Python\Python37-32›py demo.py

C: tusers\hp\AppData\Local\Programs\Python\Python37-32>pydemo.py -h

usage: demo. py [-h]

optional arguments:

-h, –help   show this help message and exit

C: \Users\hplAppData\Local\Programs\Python\Python37-32>


We covered a variety of techniques for collecting command line arguments in Python in this post, including sys, getopt, and argparse. The usefulness of these modules varies, with some offering far more than others. Getopt and argparse both require some structure, whereas sys is completely flexible. They, on the other hand, take care of the majority of the difficult job that sys leaves to you. After going over the samples, you should be able to figure out which module is ideal for your project.

Related Posts

Leave a Comment