Python parse arguments

In this tutorial we will learn to parse arguments passed to a python program through command line.

Python parse arguments

Python parse arguments Example - Learn to parse command line arguments in Python program

Just like any other programming language Python also supports command line arguments. The command line arguments are the data which is passed from command line during calling of the function. For example in a calculator python program you can pass two numbers for edition. This is one of most useful way to get dynamic values from the user of application developed in Python. The arguments also work with the program running in production environment; here any other calling program can pass the arguments to python program.

In this tutorial we are going to show you the examples of reading and parsing the command line arguments.

How to get Python Command Line Arguments?

There are few ways to read the command line arguments in Python program and you can use any of them in your programming. Here are the ways to get Python command line arguments:

  1. Python sys.argv
  2. Python getopt module
  3. Python argparse module

All these are available in python program. Let's see the examples of these one by one.

Python sys.argv

This comes with the Python sys module and it provides the sys.argv variable through which we can get command line arguments. The sys module of python parses command line argument and stores in sys.argv as a list. Then you can get command line arguments by iterating this list.

Here is simple example which prints all the command line arguments:

import sys

print("Python read command arguments example:")

#print type of sys.argv
print(type(sys.argv))

print('I received following line arguments are:')
for i in sys.argv:
    print(i)

Create test1.py with above code and then run with following command from terminal:

python test1.py one two three

This will give following output:

deepak@deepak-VirtualBox:~$ python test1.py one two three
Python read command arguments example:

I received following line arguments are:
test1.py
one
two
three
deepak@deepak-VirtualBox:~$ 

Here is screen shot of the example:

Python sys.argv parse argument example

The parameters are separated by space but if you have to pass values containing spaces then you can use double quotes. Here is an example:

deepak@deepak-VirtualBox:~$ python test1.py one "Learning Python"
Python read command arguments example:

I received following line arguments are:
test1.py
one
Learning Python
deepak@deepak-VirtualBox:~$ 

So, Python sys.argv is the easy method of getting command line arguments passed to python program.

Python getopt module

Now we will learn how to use Python getopt module to get the parameters in python program. The getopt module of Python is similar to  C getopt() function. The getopt module is used in Python for parsing command line arguments and options. We will see a small program to read command line arguments with options.

import sys, getopt

def main(argv):
   ifile = ''
   ofile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print("test.py -i <inputfile> -o <outputfile>")
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print("test.py -i <inputfile> -o <outputfile>")
         sys.exit()
      elif opt in ("-i", "--ifile"):
         ifile = arg
      elif opt in ("-o", "--ofile"):
         ofile = arg
   print ('Input file is: ', ifile)
   print ('Output file is: ', ofile)

if __name__ == "__main__":
   main(sys.argv[1:])

You can run this program with following arguments:

python test2.py -i input.txt -o out.txt

Here is the output of the program:

deepak@deepak-VirtualBox:~$ python test2.py -i input.txt -o out.txt
Input file is:  input.txt
Output file is:  out.txt
deepak@deepak-VirtualBox:~$ 

This way you can use the Python getopt module to parse arguments with options.

Python argparse module

Now we will learn how to use Python argparse module to parse input arguments in Python? The argparse module is easy to use module when you have to parse the arguments with options. In this example we are going to take two arguments with options and then print on the console. Here is example program:

# test3.py

import argparse
import sys

def check_arg(args=None):
    parser = argparse.ArgumentParser(description='Example of argparse')
    parser.add_argument('-H', '--host',
                        help='host ip',
                        required='True',
                        default='localhost')
    parser.add_argument('-p', '--port',
                        help='port of the web server',
                        default='80')


    results = parser.parse_args(args)
    return (results.host,
            results.port)

if __name__ == '__main__':
    host, port = check_arg(sys.argv[1:])
    print("Host:",host)
    print("Port:",port)

Here we have used the code:

parser.add_argument('-H', '--host',
                        help='host ip',
                        required='True',
                        default='localhost')

And this code is used to add the parameter type and its options. With the example you can construct your own parameter types while accepting from the user.

Here is the output of the program:

deepak@deepak-VirtualBox:~$ python test3.py --host roseindia.net --port 80
Host: roseindia.net
Port: 80

Here is the output of the program:

Python argparse module to parse command line argument

In this tutorial we have learned the various ways to handle command line arguments sent to python program. You learned to parse the parameters in various ways. In Python we have different options to parse command line parameters as our programming needs.

Check more tutorials at Python Tutorials.