InterviewSolution
| 1. |
How can arguments be passed from command line to a Python program? |
|
Answer» Python is an interpreted language. Its source code is not CONVERTED to a self-executable as in C/C++ (Although certain OS specific third party utilities MAKE it possible). Hence the standard way to execute a Python script is issuing the following command from command terminal. $ python hello.pyHere $ (in case of Linux) or c:\> in case of Windows is called command prompt and text in front of it is called command line contains name of Python executable followed by Python script. From within script, user input is accepted with the help of built-in input() function x=int(input('enter a number')) y=int(input('enter another number')) print ('sum=',x+y)Note that input() function always reads user input as string. If required it is converted to other data types. #example.py x=int(input('enter a number')) y=int(input('enter another number')) print ('sum=',x+y)Above script is run from command line as: $ python example.py enter a number10 enter another number20 sum= 30However, it is also possible to provide data to the script from outside by entering values separated by whitespace character after its name. All the segments of command line (called command line arguments) separated by space are stored inside the script in the form of a special list object as defined in built-in sys module. This special list object is called sys.argv Following script collects command line arguments and displays the list. import sys print ('arguments received', sys.argv)Run above script in command terminal as: $ python example.py 10 20 arguments received ['example.py', '10', '20']Note that first element in sys.argv sys.argv[0] is the name of Python script. Arguments usable inside the script are sysargv[1:] Like the input() function, arguments are always strings. They may have to be converted appropriately. import sys x=int(sys.argv[1]) y=int(sys.argv[2]) print ('sum=',x+y) $python example.py 10 20 sum= 30The command line can pass variable number of arguments to the script. Usually length sys.argv is checked to verify if desired number of arguments are passed. For above script, only 2 arguments need to be passed. Hence the script should REPORT ERROR if number of arguments is not as PER requirement. import sys x=int(sys.argv[1]) y=int(sys.argv[2]) print ('sum=',x+y) $python example.py 10 20 sum= 30import sys if len(sys.argv)!=3: print ("invalid number of arguments") else: x=int(sys.argv[1]) y=int(sys.argv[2]) print ('sum=',x+y)Output: $ python example.py 10 20 30 invalid number of arguments $ python example.py 10 invalid number of arguments $ python example.py 10 20 sum= 30 |
|