Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5)
This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python.
Command Line Arguments
Till now, we have taken input in python using raw_input() or input() [for integers]. There is another method that uses command line arguments. The command line arguments must be given whenever we want to give the input before the start of the script, while on the other hand, raw_input() is used to get the input while the python program / script is running.
For example, in the UNIX environment, the arguments ‘-a’ and ‘-l’ for the ‘ls’ command give different results.
The command line arguments in python can be processed by using either ‘sys’ module or ‘argparse’ module.
Python3
# Python code to demonstrate the use of 'sys' module # for command line arguments import sys # command line arguments are stored in the form # of list in sys.argv argumentList = sys.argv print (argumentList) # Print the name of file print (sys.argv[ 0 ]) |
OUTPUT :
['program1.py'] program1.py
NOTE : The above code runs only on command line. We need to fire the below command given that the program is saved as program1.py
python program1.py test 123
Please note the following points about the above program :
- The sys.argv takes the command line arguments in the form of a list.
- The first element in the list is the name of the file.
- The arguments always come in the form of a string even if we type an integer in the argument list. We need to use int() function to convert the string to integer.