Python | Set 6 (Command Line and Variable Arguments)
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.
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.