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. Same holds true if you want to process Command Line Arguments (CLA) in Python. There can be many options to choose from such as
There are mainly 3 ways to handle CLA in Python:
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.
# -*- coding: utf-8 -*-
# add two integers and return the sum
def add(a, b):
return a + b
# 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')
print ("\nUsage: python sys_argv.py <number1> <number2>\n")
print ("Example: python sys_argv.py 7 3\n")
if __name__ == '__main__':
# exclude script name from the argumemts list and pass it to main()
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
So when should I use or not use sys.argv?
- 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
So what do you think? Please ask any questions you may have in the comment section below and be sure to check out Part 2 of this tutorial where I discuss about
getopt in detail and you can also look into my Python and other Programming related tutorials.