Saturday 5 December 2015

Python command line arguments

Python scripts accept any number of arguments from command line. This option facilitates us to configure Application at the time of running.

How to pass command line arguments
pyhon scriptname arg1 arg2 …argN

By using ‘sys’ module we can access command line arguments.

sys.argv[0] contains file name
sys.argv[1] contains first command line argument, sys.argv[2] contains second command line argument etc.,


arithmetic.py
def sum(a, b):
  return a+b

def subtract(a, b):
  return a-b
  
def mul(a,b):
  return a*b
  
def div(a, b):
  return a/b


main.py
import arithmetic

if __name__ == "__main__":
    import sys
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    
    print(sys.argv[0])
    print("a = ", a, "b = ", b)
    print(arithmetic.sum(a,b))
    print(arithmetic.subtract(a,b))
    print(arithmetic.mul(a,b))
    print(arithmetic.div(a,b))


$ python3 main.py 10 11
main.py
a =  10 b =  11
21
-1
110
0.9090909090909091
  
$ python3 main.py 8 13
main.py
a =  8 b =  13
21
-5
104
0.6153846153846154




Previous                                                 Next                                                 Home

No comments:

Post a Comment