How to pass Command line Arguments in Python - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Hi everyone, in this tutorial, we will see different ways to use command line arguments in Python using various examples.
These are the arguments that we passed along with the executing command of Python Program in the Command-line Interface (CLI) or shell. The typical syntax for this is
python script_name.py arg1 arg2 ...
In Python, we have several ways to use the command line arguments.
The sys module is an in-built Module that provides us with the ability to interact with the Python interpreter on any platform using some variables and functions. One of the ways to interact with command line arguments is by using the variable sys.argv, which is a list of all the arguments passed during execution and having 1st element as the script name.
Let’s write a sample program that will take all the arguments from the command line and return their summation.
# importing the sys module
import sys

def summation(): 
    sum_cla = 0
    # loop over all command line arguments
    for i in sys.argv[1:]: 
        sum_cla = sum_cla + int(i)
    # printing the results    
    print("No. of command line arguments are: ",len(sys.argv[1:])) 
    print("Sum of command line arguments is:",sum_cla)
    return

if __name__ == "__main__":
    summation()
Output:
No. of command line arguments are: 4
Sum of command line arguments is: 16
Using the argparse module gives us a lot more flexibility than using the sys.argv to interact with the command line arguments as using this we can specify the positional arguments, the default value for arguments, help message etc.
argparse is the recommended command-line parsing module in the Python standard library.
The basic code to use the argeparse module is below which does nothing if no single argument is passed and will give some sort of information if it parses the argument that is known to it like -h for help.
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
Output:
python .\cla.py -h
usage: cla.py [-h]

optional arguments:
-h, --help show this help message and exit
We can add our own custom positional arguments when using the command line arguments. These type of arguments are mandatory to be passed during the execution otherwise we will get an error.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("sum",help = "It will sum the integer list passed as argument")
args = parser.parse_args()
Output:
python .\cla.py --help
usage: cla.py [-h] sum

positional arguments:
sum It will sum the integer list passed as an argument

optional arguments:
-h, --help show this help message and exit
We can add our own custom optional arguments when using the command line arguments. These type of arguments are not mandatory to be passed during the execution and are generally used to provide extra optional functionalities to the user.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("weight",help = "Return -ve is integer is negative else +ve",type=int)
parser.add_argument("--verbose", action="store_true",help="negative/ positive integer")
args = parser.parse_args()

if args.verbose:
    print("Weight=", '-ve' if args.weight<0 else '+ve')
elif args.weight <0:
    print('Integer is -ve')
else:
    print('Integer is +ve')
Output:
python .\cla.py -9 --verbose
Weight= -ve

python .\cla.py 5
Integer is +ve
The getopt module is a parser for command-line options whose API is similar to users of the C language getopt() function. If we want to write less code and get better help and error messages, we should consider using the argparse module that we have discussed above.
This module provides a methodgetopt()which parses the command line options and the parameter list. The first element of command-line arguments while using sys.argv is generally skipped. he basic syntax of this method is.
getopt.getopt(args, shortopts, longopts=[])
args – The argument list usually from the second element of Command-line interface example sys.argv[1:]
shortopts – The string of option letters that the script wants to recognize, with options that require an argument followed by a colon (:)
longopts – The list of strings with the names of the long options which should be supported.
# importing modules
import sys
import getopt

# Defining arguments and options
arguments = sys.argv[1:]
shortopts= "svo"
longopts = ["script-name ","verbose", "output="]

# Printing different options and arguments
options, args = getopt.getopt(arguments, shortopts,longopts)
print('Options are :',options)
print('Arguments are :',args)

# Setting behaviour for options
for opt, val in options: 
    if opt in ("-s", "--script-name"):
        print ("Script name is", sys.argv[0])
    elif opt in ("-o", "--output"):
        print ("Output saved in file named", val)
    elif opt in ("-v", "--verbose"):
        print ("Verbosity is ON")
Output 1:
python .\cla.py -v --output=abc.xyz a b
Options are : [('-v', ''), ('--output', 'abc.xyz')]
Arguments are : ['a', 'b']
Verbosity is ON
Output saved in file named abc.xyz
Output 2:
python .\cla.py -s --verbose --output=opfile.txt a b
Options are : [('-s', ''), ('--verbose', ''), ('--output', 'opfile.txt')]
Arguments are : ['a', 'b']
Script name is .\cla.py
Verbosity is ON
Output saved in file named opfile.txt
So we learned how to use command-line arguments in Python and if you have any doubts or queries please ask in the comment section below.
Modes of Python Program
Shell Script How to write logs in a Separate File
How to install Maven on windows 7 command line
Happy Learning 🙂

Different ways to use Lambdas in Python
How to use *args and **kwargs in Python
Modes of Python Program
How to Export MySQL Tables to a file from command line
Python String to int Conversion Example
How to get the size of a Directory in Python ?
How to Delete a File or Directory in Python
Python How to read input from keyboard
How to check whether a file exists python ?
How to Handle Exceptions in Python
What are the different ways to Sort Objects in Python ?
How to Create or Delete Directories in Python ?
How to Remove Spaces from String in Python
How to install Maven on windows 7 command line
How to access for loop index in Python

Different ways to use Lambdas in Python
How to use *args and **kwargs in Python
Modes of Python Program
How to Export MySQL Tables to a file from command line
Python String to int Conversion Example
How to get the size of a Directory in Python ?
How to Delete a File or Directory in Python
Python How to read input from keyboard
How to check whether a file exists python ?
How to Handle Exceptions in Python
What are the different ways to Sort Objects in Python ?
How to Create or Delete Directories in Python ?
How to Remove Spaces from String in Python
How to install Maven on windows 7 command line
How to access for loop index in Python
 


Δ
 Python – Introduction
 Python – Features
 Python – Install on Windows
 Python – Modes of Program
 Python – Number System
 Python – Identifiers
 Python – Operators
 Python – Ternary Operator
 Python – Command Line Arguments
 Python – Keywords
 Python – Data Types
 Python – Upgrade Python PIP
 Python – Virtual Environment
 Pyhton – Type Casting
 Python – String to Int
 Python – Conditional Statements
 Python – if statement
 Python – *args and **kwargs
 Python – Date Formatting
 Python – Read input from keyboard
 Python – raw_input
 Python – List In Depth
 Python – List Comprehension
 Python – Set in Depth
 Python – Dictionary in Depth
 Python – Tuple in Depth
 Python – Stack Datastructure
 Python – Classes and Objects
 Python – Constructors
 Python – Object Introspection
 Python – Inheritance
 Python – Decorators
 Python – Serialization with Pickle
 Python – Exceptions Handling
 Python – User defined Exceptions
 Python – Multiprocessing
 Python – Default function parameters
 Python – Lambdas Functions
 Python – NumPy Library
 Python – MySQL Connector
 Python – MySQL Create Database
 Python – MySQL Read Data
 Python – MySQL Insert Data
 Python – MySQL Update Records
 Python – MySQL Delete Records
 Python – String Case Conversion
 Howto – Find biggest of 2 numbers
 Howto – Remove duplicates from List
 Howto – Convert any Number to Binary
 Howto  – Merge two Lists
 Howto – Merge two dicts
 Howto – Get Characters Count in a File
 Howto – Get Words Count in a File
 Howto – Remove Spaces from String
 Howto –  Read Env variables
 Howto – Read a text File
 Howto – Read a JSON File
 Howto –  Read Config.ini files
 Howto – Iterate Dictionary
 Howto – Convert List Of Objects to CSV
 Howto – Merge two dict in Python
 Howto – create Zip File
 Howto – Get OS info
 Howto – Get size of Directory
 Howto – Check whether a file exists
 Howto –  Remove key from dictionary
 Howto – Sort Objects
 Howto – Create or Delete Directories
 Howto – Read CSV File
 Howto – Create Python Iterable class
 Howto – Access for loop index
 Howto – Clear all elements from List
 Howto – Remove empty lists from a List
 Howto – Remove special characters from String
 Howto – Sort dictionary by key
 Howto – Filter a list