How to use sys.argv In Python
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.
Python3
# 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:
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.argv
- Using getopt module
- Using argparse module
Contact Us