Monday, 27 May 2019

Command Line arguments

                                  Command Line arguments
Type any program, save that file

Ex2: To display command line args, save this as com2.py
import sys
n=len(sys.argv)#N IS THE NO OF ARGUMENTS
args=sys.argv#args list contains arguments
print('no. of command line args= ',n)
print('The args are: ',args)
print('the args one by one: ')
for a in args:
    print(a)

Note: Now you give the input values from command line like below:.
"""output
C:\>f:
F:\>cd programs
F:\Programs>python com2.py 2 4
Here 2 and ‘New Delhi’ are command line arguments
The arguments (parameters/input values) which are passing at the time of execution from the command prompt is called command line arguments.

Here argv is not an array.
Within the python program, this command line arguments are available in argv. Which is present in SYS module.

Here argv[0] represents name of the program. But not first command line argument. Argv[1] represents first command line argument.

Example program:
#ex3.py
#ex3.py
import sys
n=len(sys.argv)
k=sys.argv
print("n=",n)
print("command line arguments are :")
print(k)

Steps to execute this program:

1. Go to the command prompt:
2.  Move to your programs folder

C:\Users\myraj>f:
F:\>cd programs
F:\Programs>cd command
F:\Programs\command>python ex3.py 1 2 3 New Delhi
n= 5
command line arguments are :
['ex3.py', '1', '2', '3', 'Hyd']

F:\Programs\command> 

All the command line arguments are stored in the form of the strings.

If you observe the above output, we passed only 2 arguments
But stored 3 arguments, the reason is ‘New Delhi’ has two words because of space, so it took as two arguments instead of one. But how to make this “New Delhi” as a single argument?

‘ “New Delhi”’ or “ ‘New Delhi’”

All the command line arguments are stored in the form of the strings.
>>> import sys
>>> n=len(sys.argv)
>>> k=sys.argv
>>> type(k)
<class 'list'>

>>> 
#sum of two numbers
import sys
a=sys.argv
#convert arguments into two nuers
#sum=int(sys.argv[1])+int(sys.argv[2])
sum=int(a[1])+int(a[2])
print(sum)
"""
F:\Programs>cd command
F:\Programs\command>python 2.py 2 4
6
To find sum of even numbers
#find sum of even numbers
import sys
a=sys.argv[1:]
print(a)
sum=0
#find sum of even numbers
for i in a:
    n=int(i)
    if n%2==0:
        sum+=n
print('sum of evens numbers are=',sum)
"""output
F:\Programs\command>python 3.py 10 4 6 7 9
['10', '4', '6', '7', '9']
sum of evens numbers are= 20
"""



No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...