Command line arguments are quite old, in the days of DOS they were generally just options enabling/disabling mechanism and were known as switches. But, after the growth of *nix systems command line arguments have been developed and have provided a lot of features to power users.

Here's an example of a command line argument.

Code:

[pradeep@home-desktop]$ ls -lh --color='yes'

Now, you can pass switches, values, single & multiple, it does not always need to be in a specific order, you can pass multiple arguments at once. There are two types of options, short options (are single characters), like l & h in the above sample, and long options (are more than 1 character) which are preceded by 2 hipens (-).

In this article we'll be looking at making your Python program read command line arguments.

Basics

To learn about reading command line parsing, let's first look at how Python reads command line arguments natively, it needs to be in a specific order as there is no parsing as such, just arguments that were passed from the shell. Follow the example below.

Using getopt

getopt module parses the command line arguments and processes them using the config that is provided to it. getopt accepts 3 arguments, first a list of arguments that need to be parsed, next is the list of options that need to be looked for, if an option should accompany a value it should be followed by : symbol (like in the example below, option i can have a value, whereas others are just switches), and the last optional parameter is long options for the previously specified short option, they should be specified in the same order as the short options. Try the example below: