April 14, 2020

How to pass command line arguments in Python?

Handling command line arguments with Python
  • There are number of different ways of handling command line arguments in Python 3. 
  • 'sys' module is the built-in way. 
  • We can also use getopt module, which handles both short and long options, including the evaluation of the parameter values.
  • argparse module, which is derived from the optparse module available up to Python 2.7, we can also use it to handle command line arguments.
  • The other method is using the docopt module, which is available on GitHub.

sys Module and sys.argv
  • 'sys' a basic module that has been shipped with Python from the early days. This module implements the command line arguments in a simple list structure named sys.argv.
  • argv represents all the items that come along via the command line input, it's basically an array holding the command line arguments of our program. FYI, the counting starts at zero (0) not one (1).
  • To use 'sys.argv', we need to first import sys.
  • The first argument, sys.argv[0], is always the name of the program from where it was invoked. The rest of the list elements, sys.argv[1] to sys.argv[n], are the command line arguments 2 through n. A space is used as a delimiter between the arguments. If the argument values contains a space in it, we have to be surrounded by quotes in order to be properly parsed by sys.
  • We get check/ get how many arguments have been entered by using len(sys.argv).
GIT URL: Handling command line arguments in Python using 'sys' module

Let's create a python file with name passCmdArgs.py.

If we run the above program with "python passCmdArgs.py first", output would be:

Let's modify the above example for 2 parameters:

If we execute the above program by passing only one parameter, it will throw "IndexError: list index out of range".


Iterating Through Arguments using for loop

Let's execute above program by passing 2 parameters (first, second)


Iterating Through Arguments using while loop

-K Himaanshu Shuklaa..

No comments:

Post a Comment

RSSChomp Blog Directory