argparse.Namespace in Python

In this tutorial, we are going to discuss argparse and argparse.Namespace in Python. Here you will gain some knowledge to deal with Command-Line arguments in Python.

Command-Line: argparse and argparse.Namespace in Python

We all know many ways to get the user input in Python. But we generally don’t know how to use the Command Line argument for user input in the case of Python.

  • Command Line input is that input to the program which has taken during the execution of the program. We usually use to write the file name followed by the user inputs. For example:-
$ python file_name.py _user_input_
  • argparse:This is a Parser for the command-line option, arguments, and subcommands.

The argparse module makes the user input easy with the command-line. The command-line input is more user-friendly and easy to implement in any programming language. In Python, we use argparse for such purpose. The argparse is compatible with Python 2.7 and later. In the older version Python use optparse for the command-line.

 

argparse.Namespace

Class argparse.Namespace is a simple class used for creating an object by parse_args() which holds the attributes and returns it. This class is a subclass of Object class with a very simple and readable string representation. We can get a dictionary-like structure of the attributes stored in it using vars() in Python.

>>> import argparse
>>> vars(argparse.Namespace)
mappingproxy({'__module__': 'argparse', '__doc__': 'Simple object for storing attributes.\n\n
Implements equality by attribute names and values, and provides a simple\n
string representation.\n    ', '__init__': <function Namespace.__init__ at 0x02BA81E0>,
 '__eq__': <function Namespace.__eq__ at 0x02BA8228>,
 '__contains__': <function Namespace.__contains__ at 0x02BA8270>, '__hash__': None})
  • The above commands give the internal structure of class argparse.Namespace. It also shows all attributes in the dictionary format.
  • When we define all arguments, we can use the parse_args() for parsing a sequence of string. The method parse_args() returns a Namespace object, which contains the attributes to the command.

Simple Example:-

Let below block of code is written in a file named argpars.py 

import argparse

parser = argparse.ArgumentParser(description='Process some numbers.')

parser.add_argument('num', type=int,help='an integer for the accumulator')
parser.add_argument('--sum', action='store_const',const=sum, default=min,
                    help='sum the integers (default: find the min)')

args = parser.parse_args()
print(args.accumulate(args.num))

*** Now the above file argpars.py can be run at the command-line and provide the helpful message.


$python prog.py
usage: argpars.py [-h] [--sum] num
argpars.py: error: the following arguments are required: num
$ 

***  We run the above file without any input with file name so it gives some help and error providing that num is required. Now I run above code with some input(as shown below).


$python prog.py 1 2 3 4 5
1             //--> By default this gives us minimum value
$python prog.py 1 2 3 4 5 --sum
15            //--> Sum of value

For the above example, we have 3 steps

  • Creating a parser:- Firstly, we need to create an ArgumentParser object using the argparse
>>> parser = argparse.ArgumentParser(description='Process some numbers.')
  • Adding Arguments:Secondly, we use the add_argument() method, it takes the string from the command-line and turns it into a Python object.
>>> parser.add_argument('num', type=int,help='an integer for the accumulator')
  • Parsing argument:- At last, we have to take the command-line input and convert each argument into the appropriate data type and then invoke appropriate action. In this step, we use parse_args() method
>>> args = parser.parse_args() 

 

Thank You.
Know more


Also read:-

Memory Management in Python
How to print different output in same line ?
Find the memory Address of a variable in Python

Leave a Reply

Your email address will not be published. Required fields are marked *