Command Line Arguments in Python
Last Updated :
20 Jun, 2024
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. The three most common are:
Using sys.argv
The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
One such variable is sys.argv which is a simple list structure. It’s main purpose are:
- It is a list of command line arguments.
- len(sys.argv) provides the number of command line arguments.
- sys.argv[0] is the name of the current Python script.
Example: Let’s suppose there is a Python script for adding two numbers and the numbers are passed as command-line arguments.
Python
# Python program to demonstrate
# command line arguments
import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("\nName of Python script:", sys.argv[0])
print("\nArguments passed:", end = " ")
for i in range(1, n):
print(sys.argv[i], end = " ")
# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)
Output:

Using getopt module
Python getopt module is similar to the getopt() function of C. Unlike sys module getopt module extends the separation of the input string by parameter validation. It allows both short, and long options including a value assignment. However, this module requires the use of the sys module to process input data properly. To use getopt module, it is required to remove the first element from the list of command-line arguments.
Syntax: getopt.getopt(args, options, [long_options])
Parameters:
args: List of arguments to be passed.
options: String of option letters that the script want to recognize. Options that require an argument should be followed by a colon (:).
long_options: List of string with the name of long options. Options that require arguments should be followed by an equal sign (=).
Return Type: 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.
Example:
Python
# Python program to demonstrate
# command line arguments
import getopt, sys
# Remove 1st argument from the
# list of command line arguments
argumentList = sys.argv[1:]
# Options
options = "hmo:"
# Long options
long_options = ["Help", "My_file", "Output="]
try:
# Parsing argument
arguments, values = getopt.getopt(argumentList, options, long_options)
# checking each argument
for currentArgument, currentValue in arguments:
if currentArgument in ("-h", "--Help"):
print ("Displaying Help")
elif currentArgument in ("-m", "--My_file"):
print ("Displaying file_name:", sys.argv[0])
elif currentArgument in ("-o", "--Output"):
print (("Enabling special output mode (% s)") % (currentValue))
except getopt.error as err:
# output error, and return with an error code
print (str(err))
Output:

Using argparse module
Using argparse module is a better option than the above two options as it provides a lot of options such as positional arguments, default value for arguments, help message, specifying data type of argument etc.
Note: As a default optional argument, it includes -h, along with its long version –help.
Example 1: Basic use of argparse module.
Python
# Python program to demonstrate
# command line arguments
import argparse
# Initialize parser
parser = argparse.ArgumentParser()
parser.parse_args()
Output:

Example 2: Adding description to the help message.
Python
# Python program to demonstrate
# command line arguments
import argparse
msg = "Adding description"
# Initialize parser
parser = argparse.ArgumentParser(description = msg)
parser.parse_args()
Output:

Example 3: Defining optional value
Python
# Python program to demonstrate
# command line arguments
import argparse
# Initialize parser
parser = argparse.ArgumentParser()
# Adding optional argument
parser.add_argument("-o", "--Output", help = "Show Output")
# Read arguments from command line
args = parser.parse_args()
if args.Output:
print("Displaying Output as: % s" % args.Output)
Output:

Command Line Arguments in Python – FAQs
How to start a Python command line?
To start a Python command-line interface (CLI), commonly referred to as a Python shell or REPL (Read-Eval-Print Loop), you typically open your terminal or command prompt and type python (or python3 on some systems) and press Enter. This opens the Python interactive interpreter where you can execute Python code interactively.
How to get number of command line arguments in Python?
You can get the number of command-line arguments passed to a Python script using len(sys.argv), where sys.argv is a list that contains all command-line arguments.
import sys
num_args = len(sys.argv)
print(f"Number of command-line arguments: {num_args}")
What is Python command line description?
Python command-line description typically refers to the ability to pass arguments or options to a Python script when running it from the command line. These arguments can be used to customize the behavior of the script, provide input data, or control its execution flow.
What is a key argument in Python?
In Python, a “key argument” generally refers to a named argument or keyword argument that you can pass to a function or method. Keyword arguments are specified by their parameter names followed by an equals sign and a value (key=value). They allow you to specify arguments in any order and provide default values for function parameters.
How to handle command-line arguments with spaces or special characters?
Command-line arguments in Python are typically handled as strings, and spaces or special characters within them are treated as part of the string. To handle them properly:
- Enclose arguments with spaces in quotes: If you need to pass arguments with spaces, enclose the entire argument within double quotes (
"). - Escape special characters: If your argument contains special characters that may have a specific meaning in the shell (like
$, &, *, etc.), you can escape them using backslashes (\).
python myscript.py "argument with spaces"
python myscript.py argument\$with\*special\&characters
Similar Reads
Command Line Arguments in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. The three most common are:Â Using sys.argvUsing getopt moduleUsing argparse moduleU
5 min read
Pass list as command line argument in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. One of them is sys module. sys Module A module is a file containing Python definiti
3 min read
Python | Set 6 (Command Line and Variable Arguments)
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers].
2 min read
Default arguments in Python
Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value. Default Arguments: Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argu
7 min read
Passing function as an argument in Python
A function can take multiple arguments, these arguments can be objects, variables(of same or different data types) and functions. Python functions are first class objects. In the example below, a function is assigned to a variable. This assignment doesnât call the function. It takes the function obj
5 min read
Python function arguments
In Python, function arguments are the inputs we provide to a function when we call it. Using arguments makes our functions flexible and reusable, allowing them to handle different inputs without altering the code itself. Python offers several ways to use arguments, each designed for specific scenari
3 min read
Tuple as function arguments in Python
Tuples have many applications in all the domains of Python programming. They are immutable and hence are important containers to ensure read-only access, or keeping elements persistent for more time. Usually, they can be used to pass to functions and can have different kinds of behavior. Different c
2 min read
How to Print Multiple Arguments in Python?
An argument is a value that is passed within a function when it is called.They are independent items, or variables, that contain data or codes. During the time of call each argument is always assigned to the parameter in the function definition. Example: Simple argument [GFGTABS] Python def GFG(name
3 min read
code.compile_command() in Python
With the help of code.compile_command() method, we can compile the single or multiple lines of code to check for the syntax error if any by using code.compile_command() method. Syntax : code.compile_command(code) Return : Return the object or compilation error if any. Example #1 : In this example we
1 min read
Types of Arguments in Python
Arguments are the values passed inside the parenthesis of the function. A function can have any number of arguments separated by a comma. There are many types of arguments in Python . In this example, we will create a simple function in Python to check whether the number passed as an argument to the
3 min read