Recent Posts

Argparse Module in python 3x

argparse – Command line option and argument parsing is a module that help you to pass value through command line and give helps if you not giving valid argument. The implementation of argparse supports features that would not have been easy to add to optparse, and that would have required backwards-incompatible API changes, so a new module was brought into the library instead. optparse is still supported, but is not likely to receive new features and also in python 3x it is better to use argparse.

Now its time to make some sense.
we are going to create a file named argsFin.py

I user here terminal of linux, if you are a windows user u can do it from cmd or power shell.







 import argparse

def fibon(n):
    a , b = 0,1
    for i in range(int(n)):
        a , b = b , a+b
    return str(a)

def Main():
    argement = argparse.ArgumentParser() #The first step in using the argparse is creating an ArgumentParser object
    argement.add_argument('num',help='It will create the \'n\'th finbonacci number ',type = int )
    # The first argument is variable name,2nd argement is help message, 3rd argument is variable type
    args = argement.parse_args() # passing the argument into args
    print('The',str(args.num),'finbonacci number is ',fibon(str(args.num)))

if __name__ == '__main__' : Main()

Here i tell you how the program works.
First we make fibon function.It calculate the Fibonacci number depends on n parameter. The main() function is use for argument passing. First we create a object of argparse module. Then we add 'argement' into that object. The object which is add into 'argement' is have our passed parameter which we give through command line. Then we create an function type variable named args. In args we have the argument now and the variable is 'num'. So we called it by only dot.


Here is the output of the program.

When we need help
root@root:~/Desktop/python/practice# python3.4 argsFin.py --help
usage: argsFin.py [-h] num

positional arguments:
  num         It will create the 'n'th finbonacci number

optional arguments:
  -h, --help  show this help message and exit

When we pass valid argument
root@root:~/Desktop/python/practice# python3.4 argsFin.py 6
The 6 Fibonacci number is  8

When we pass wrong argument
root@root:~/Desktop/python/practice# python3.4 argsFin.py ds
usage: argsFin.py [-h] num
argsFin.py: error: argument num: invalid int value: 'ds'

Post a Comment

0 Comments