- the concept of passing the arguments from command line at the time of running the python program/file,that type of arguments are called command-line arguments.
- file name also taken as a one of the command line argument.
- all the command line arguments are stored into list object in the form of strings, that list object stored into the "argv" variable of sys module.
Example:
import sys
print(sys.argv)
print(len(sys.argv))
for p in sys.argv:
print(p)
Output1:
C:\Desktop>python commandlineargument.py hai siva krishna
['commandlineargument.py', 'hai', 'siva', 'krishna']
4
commandlineargument.py
hai
siva
krishna
Output2:
C:\Desktop>python commandlineargument.py arg1 arg2 arg3
['commandlineargument.py', 'arg1', 'arg2', 'arg3']
4
commandlineargument.py
arg1
arg2
arg3
Example:
import sys
if len(sys.argv)==3:
try:
x=int(sys.argv[1])
y=int(sys.argv[2])
z=x+y
print(z)
except(ValueError):
print("enter numerical values only")
else:
print("enter two userdefined arguments only")
Output1:
C:\Desktop>python commandlineargument.py 4 5
9
Output2:
C:\Desktop>python commandlineargument1.py 4
enter two userdefined arguments only
Output3:
C:\Desktop>python commandlineargument1.py 4 abc
enter numerical values only
Valuable post useful for everyone. Keep on sharing.
ReplyDeletePython Training in Hyderabad
Python Training
Python Online Training