Introduction to Python argparse
The argparse module was an addition to Python 2.7 as a replacement of the pre-existing module named optparse. The new module contains the implementation of several functionalities that would have been quite difficult additions to the pre-existing ones, which is the backwards-incompatible API changes. The initial step of using argparse module is creating a parser object first and then letting it know what arguments to expect. Finally, this parser can then be utilized to read the command line arguments during your python program’s run time process. ArgumentParser is the parser class. The constructor object requires several arguments in order to set up the desc used.
parser = argparse.ArgumentParser(description='This is default value of desc')
- Here we have imported the argparse module using the import statement.
- Then an argument parser object is created named “parser”.
- The default argument value for the “description” is also set.
How does Parsing in Command-Line works?
Once we have defined all of the arguments, we can pass the sequence of arguments as strings to the below function.
- parse_args(): If we do not pass the arguments to this function, then the arguments will be taken up from sys.argv[1:], by default.
- GNU/POSIX syntax is utilized to process the options further, so you can also pass the options and arguments in a mixed sequence, and it will not impact the process.
- Finally, the parse_args() function will return a value, which indeed is the namespace that consists of arguments to the command.
- The object holds the argument value as an attribute. If the argument dest is “myopt”, then you can use the command in the below-mentioned format to access that value myopt.
How does Python argparse() Work?
Given below examples shows the working of python argparse():
How argparse() works in python.
parser = argparse.ArgumentParser(description='Understand functioning')
parser.add_argument('-x', action="store_true", default=False)
parser.add_argument('-y', action="store", dest="y")
parser.add_argument('-z', action="store", dest="z", type=int)
print (parser.parse_args(['-x', '-yval', '-z', '3']))
- To a single character option, there are multiple ways in which the values can be passed.
- The value type linked with ‘z’ in the above program’s output is an integer, as we had specifically mentioned to the ArgumentParser to convert the argument before storing it.
- Moreover, “Long” option names, having one or more characters in their names, are also handled in a similar fashion in python.
How argparse() deals with “Long option names”.
parser = argparse.ArgumentParser(description='How argparse() deals with Long option names')
parser.add_argument('--noargument', action="store_true", default=False)
parser.add_argument('--withargument', action="store", dest="witharg")
parser.add_argument('--withargument2', action="store", dest="witharg2", type=int)
print (parser.parse_args([ '--noargument', '--withargument', 'val', '--withargument2=3' ]))
- And the results are similar, this validating the notion of “Long” option names, having one or more characters in their names are also handled in a similar fashion in python.
Argument Actions While using argparse() in Python
Whenever an argument is encountered, there are six built-in actions that can be instantaneously triggered.
- store: It converts the value into a different type first and then stores the same. By default, this is the action that comes into the picture if any other is not defined.
- store_const: Rather than saving the value that is coming up from the argument passed, it saves the value that is defined as a part of the argument specification itself.
- store_true / store_false: This action is utilized to take care of the boolean switches when it comes to using the argparse() functionality. Primarily, it is utilized to save the boolean values.
- append: If in case the arguments are repeated during the usage of argparse() function, then append action is used to save these multiple values in the form of a list.
- append_const: If in case the arguments are repeated in the argument specification during the usage of argparse() function, then append_const action is used to save these multiple values in the form of a list.
- version: version action is utilized to print the version details about the program.
Advantages of Python argparse Library
Given below are the advantages of Python argparse Library:
- It allows setting the name of the program.
- Enables to view the custom usage help.
- Moreover, Text help for both before and after the arguments.
- The prefix charts can also be customized using the argparse python library.
- Moreover, Prefix can also be set for the files that contain the arguments.
- It also enables the feature of allowing and disallowing the abbreviations.
- Action to be taken 0ver the argument can be pre-set using the python argparse library.
- The num of values that are taken up by the option can also be set beforehand itself.
Python argparse() is one of the recommended python modules that take care of multiple scripting needs in an automated fashion by enabling the developer to create reproducible scripts right away from the jupyter notebook code. argparse() enables the user to provide values for the variables during the runtime process.
This is a guide to Python argparse. Here we discuss the Introduction, how parsing in the command line works, how python argparse() work, etc. You may also have a look at the following articles to learn more –