Executing functions with multiple arguments at a terminal in Python
Last Updated :
02 Sep, 2020
Commandline arguments are arguments provided by the user at runtime and gets executed by the functions or methods in the program. Python provides multiple ways to deal with these types of arguments. The three most common are:
- Using sys.argv
- Using getopt module/li>
- Using argparse module
The Python sys module allows access to command-line arguments with the help of sys module. The python sys module provides functions and variables that can be used to access different parts of the Python Runtime Environment. It allows access to system-specific parameters and functions. To use the sys module we need to import the sys module in our program before running any functions.
There are mainly two functions in the sys module:
sys.argv: gives the list of command-line arguments. For example, sys.argv[0] is the program name.
len(sys.argv): gives the number of command-line arguments.
Example 1 : This program demonstrates the use of sys.argv to fetch the command line arguments and len(sys.argv) gives the total number of command line arguments passed including the name of the python script.
Python3 1==
# importing the module
import sys
# storing the arguments
program = sys.argv[0]
arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]
# displaying the program name
print("Program name : " + program)
# displaying the arguments
print("arg1 : " + arg1)
print("arg2 : " + arg2)
print("arg3 : " + arg3)
print("Number of arguments : ", len(sys.argv))
print(sys.argv)
Output :
Example 2 : This program demonstrates how command line arguments are passed into a function using sys.argv[index]. The command line arguments at index 1, 2 and 3 are stored into the variables arg1, arg2 and arg3. The variables arg1, arg2 and arg3 are passed to the function defined. However, the command line arguments can be passed directly without storing its value in local variables.
Python3 1==
# importing the module
import sys
# function definition
def concat(s1, s2, s3):
print(s1 + " " + s2 + " " + s3)
# fetching the arguments
arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]
# calling the function
concat(arg1, arg2, arg3)
Output :
Example 3 : This program demonstrates how command line arguments are passed into a function using sys.argv[index]. The command line arguments at index 1 and 2 are stored into the variables arg1 and arg2. The variables a and b are passed to the function defined. Command line arguments are accepted as strings, hence in order to perform numerical operations it should be converted into the desired numeric type first. For example, in this program the command line argument is converted into integer first and then stored into the variables. However, the command line arguments can be passed directly without storing its value in local variables.
Python3 1==
# importing the module
import sys
# function definition
def add(a, b):
print("Result", a + b)
# fetching the arguments
arg1 = int(sys.argv[1])
arg2 = int(sys.argv[2])
# displaying the arguments
print(arg1, arg2)
# calling the function
add(arg1, arg2)
Output :
Using argparse module
There is a certain problem with sys.argv method as it does not throw any specific error if the argument is not passed or argument of invalid type is passed. The argparse module gracefully handles the absence and presence of parameters. The following examples show the utility of argparse module:
Python3 1==
# importing the module
import argparse
# creating an ArgumentParsert object
parser = argparse.ArgumentParser()
# fetching the arguments
parser.add_argument('number',
help = "Enter number to triple it.")
args = parser.parse_args()
# performing some operation
print(args.number * 2)
Output :

Python by default accepts all command line arguments as string type hence the result is 55 ie. the string gets repeated twice. However, we can specify the data type we are expecting in the program itself so that whenever a command line argument is passed it is automatically converted into expected data type provided it is type compatible.
Python3 1==
# importing the module
import argparse
# creating an ArgumentParsert object
parser = argparse.ArgumentParser()
# fetching the arguments
parser.add_argument('number',
help = "Enter number to double.",
type = int)
args = parser.parse_args()
print(args.number * 2)
Output :

We can look at the errors generated :

This argparse throws specific error unlike the sys module. Any of the modules can be used as per convenience and requirement.
Python provides a
getopt module that enables parsing command-line arguments.
Example :
Python3
import sys
import getopt
def full_name():
first_name = None
last_name = None
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "f:l:")
except:
print("Error")
for opt, arg in opts:
if opt in ['-f']:
first_name = arg
elif opt in ['-l']:
last_name = arg
print( first_name +" " + last_name)
full_name()
Output :
Similar Reads
Passing Dictionary as Arguments to Function - Python
Passing a dictionary as an argument to a function in Python allows you to work with structured data in a more flexible and efficient manner. For example, given a dictionary d = {"name": "Alice", "age": 30}, you can pass it to a function and access its values in a structured way. Let's explore the mo
4 min read
How to pass argument to an Exception in Python?
There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the fol
2 min read
How to bind arguments to given values in Python functions?
In Python, binding arguments to specific values can be a powerful tool, allowing you to set default values for function parameters, create specialized versions of functions, or partially apply a function to a set of arguments. This technique is commonly known as "partial function application" and ca
3 min read
How to Call Multiple Functions in Python
In Python, calling multiple functions is a common practice, especially when building modular, organized and maintainable code. In this article, weâll explore various ways we can call multiple functions in Python.The most straightforward way to call multiple functions is by executing them one after a
3 min read
Pass function and arguments from node.js to Python
Prerequisites: How to run python scripts in node.js using the child_process module. In this article, we are going to learn how to pass functions and arguments from node.js to Python using child_process. Although Node.js is one of the most widely used web development frameworks, it lacks machine lear
4 min read
Run function from the command line In Python
Python is a flexible programming language with a wide range of uses that one of Pythonâs most useful ones is its ability to execute functions from the command line. Especially this feature is very useful when it comes to automation and scripting etc. In this article, Iâll explain how to execute a Py
4 min read
How to handle invalid arguments with argparse in Python?
Argparse module provides facilities to improve the command-line interface. The methods associated with this module makes it easy to code for command-line interface programs as well as the interaction better. This module automatically generates help messages and raises an error when inappropriate arg
4 min read
Check multiple conditions in if statement - Python
If-else conditional statement is used in Python when a situation leads to two conditions and one of them should hold true. Syntax:if (condition): code1else: code2[on_true] if [expression] else [on_false]Note: For more information, refer to Decision Making in Python (if , if..else, Nested if, if-elif
4 min read
Python Function Parameters and Arguments
Parameters are variables defined in a function declaration. This act as placeholders for the values (arguments) that will be passed to the function. Arguments are the actual values that you pass to the function when you call it. These values replace the parameters defined in the function. Although t
3 min read
Assigning multiple variables in one line in Python
A variable is a segment of memory with a unique name used to hold data that will later be processed. Although each programming language has a different mechanism for declaring variables, the name and the data that will be assigned to each variable are always the same. They are capable of storing val
2 min read