Sea of Tranquility    About    Archive    Feed

Undertsanding Command line Arguments in Python

Often, passing arguments to a programme through the command line is a useful option. Python’s argparse moduel provides the necessary tools for achieving this.

Passing command line arguments involves the following steps:

  1. Import ArgumentParser class from argparse module
  2. Create an instance of ArgumentParser
  3. List out the arguments that you pass on through the command line
  4. Ask the program to inspect the command line for arguments and store them into computer memory.

These steps can be implemented as given below:

import argparse
x = argparse.ArgumentParser() # x is an instance of the class ArgumentParser
x.add_argument("p")
x.add_argument("q")
arguments = x.parse_args() # saving command line arguments into computer memory

print(arguments) # print the arguments provided

The print() statement at the end confirms that the arguments provided via command line are indeed stored in the variable arguments.

Now, let’s dig a little deeper and find the datatype of the stored values.

print(type(arguments.p), type(arguments.q))

The output of the above command clearly shows that both of them are stored as strings. In fact, unless specified, argparse treats arguments as strings. Therefore, if we want to compute something, we need to specifically ask argparse to consider the parameters as numbers (either integer or floating point number).

x.add_argument("p", type = int)
x.add_argument("q", type = int)

With this, we are in a position to do something useful. As an example, given below is a programme that takes two numbers from the command line and does some calculations using them.

def square(x):
    return x*x

def cube(x):
    return x*x*x

def main():
    from argparse import ArgumentParser

    x = ArgumentParser()
    x.add_argument("p", type = int)
    x.add_argument("q", type = int)
    arguments = a.parse_args()
    print(square(arguments.p) + cube(arguments.q))

if __name__ == "__main__":
    main()