How to use argparse module In Python
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.
Python3
# 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.
Python3
# 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
Python3
# 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
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