In the programming world, an expression often comes across that “a problem can be solved in many different ways”. Hence the programmer has to decide which solution is best for him/her. The same holds true if you want to process Command Line Arguments (CLA) in Python. There can be many options to choose from such as
Let us look at each option in detail. We will be writing a simple python script to add two numbers and see which of the three is suitable for use in what scenarios.
argvis a variable provided by the
sysmodule which holds a list of all the arguments passed to the command line (including the script name).
- So even if you don’t pass any arguments to your script. The
argvvariable always contains at least one element i.e the script name.
- The arguments in argv are always parsed as
string. So be careful if you are expecting your input to be of any other type. You may need to cast or convert the elements according to your requirements.
#!/usr/bin/python # -*- coding: utf-8 -*- import sys # add two integers and return the sum def add(a, b): return a + b def main(argv): # make sure there are at least two arguments if len(argv) >= 2: # convert arg 0 and 1 to int and pass them to add function print ('\n Sum of two numbers is :', add(int(argv), int(argv)), '\n') else: print ("\nUsage: python sys_argv.py <number1> <number2>\n") print ("Example: python sys_argv.py 7 3\n") sys.exit(2) if __name__ == '__main__': # exclude script name from the argumemts list and pass it to main() main(sys.argv[1:])
sys.argvis of the type
<list>so you can access the elements just as you would from any other list. For example,
- As you can see on line 26 I am excluding the script name (
arg 0) before passing it to the
- As you can see
sys.argvis just a list of command line arguments and does not provide any additional features such as the option for switches ( ex: as in
ls -l) or specifying the data type of arguments nor the ability to have position independent arguments ( ex: long listing of files works as expected even if you specify the option at last like
- It does not provide any inherent mechanism to make any of the arguments as
optionaland we also cannot limit the number of arguments supplied to our script.
- However, this can be more than sufficient if your problem definition is simple enough. But if your requirements are a bit more advanced than just adding two numbers, you may need to use