
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Access Command Line Arguments in Python
The command line is the place where executable commands are given to the operating system. In Python, command-line arguments allow users to pass information to a script when it's executed from the terminal.
A Python script can be executed by writing its name in front of the Python executable on the command line. Following is the example command which executes the Python file named sample.py -
python sample.py
If we need to pass arguments to a script, we can pass them at the time of execution, separating them by a space as shown below -
python test.py Hello TutorialsPoint
Python provides various ways to handle the command line arguments, they are -
- Using a sys.argv[] list
- Using argparse Module
- Using getopt Module
Using a sys.argv[]
The sys.argv list in Python is used to access command-line arguments passed to a script. This method is useful for handling simple inputs from the command line.
For example, let us assume we are trying to pass two strings as arguments to the Python file test.py while executing it through the command line -
python test.py Hello TutorialsPoint
This program's List object would then contain the following -
sys.argv[]=['test.py', 'Hello', 'TutorialsPoint']
test.py:
In the Python program, we can access these arguments as shown below -
import sys print ("first command line argument: ",sys.argv[1]) print ("second command line argument: ",sys.argv[2])
Following is the output of the above program -
first command line argument: Hello second command line argument: Tutorialspoint
Using argparse Module
The argparse module is a built-in module that reduces boilerplate code and makes our code more robust. It is better than using the special List Object argv[] as the argparse module handles all the standard use cases, such as subcommands, generates the help and its usage for us, checks and sanitizes the user input, which argv[] fails to do.
Example
Following is an example which shows how to access command line arguments with the help of argparse module -
import argparse parser = argparse.ArgumentParser("simple_example") parser.add_argument('student_id', type=str, help='Show student_id') args = parser.parse_args() print("The Student Exists with ID:") print(args.student_id)
Following command can be used in the command line to execute the above python script using argparse module -
python test.py 2000133
The output of the above program will be as follows ?
The Student Exists with ID: 2000133
Using the getopt Module
Python provides the getopt module is used to parse the command line arguments in a program. The API is designed similarly to the getopt() function in the C programming language, so it supports the same conventions as the function.
This module provides a method with the same name getopt(). It is used to access the command line arguments. Following is the syntax of this method -
getopt.getopt(args, shortopts, longopts=[])
The following are the parameters of the getopt() function: args, shortopts, and longopts.
Where,
- args is the list of command-line arguments.
- shortopts are the string of option letters. It takes the arguments which are followed by a colon f:.
- Longopts is a list of strings with the names of long options. This option requires arguments that should be followed by an equal sign (=).
This method is equivalent to sys.args[1:], i.e., it does not access the reference of the program.
Example
The following example shows the usage of getopt.getopt() method to parse through the command line arguments -
import sys import getopt def welcome(): first_arg = None next_arg = None argv = sys.argv [1:] try: opts , args = getopt.getopt (argv, "f:n:") except: print ("Error") for opt , arg in opts: if opt in ['-f']: first_arg = arg elif opt in ['-n']: next_arg = arg print (first_arg + " " + next_arg) welcome()
We can execute the above program by passing the two arguments through the command line -
python test.py -f Hello -n Tutorialspoint!
Following is the output of the above program -
Hello Tutorialspoint!