Command Line Arguments


Using the 'sys.argv'

The 'argv' is a method of the 'sys' module that returns a list of all the arguments that have been passed on the command line while invoking the python file. Since the method is part of the 'sys' module, the module has to be imported first.

Refer to the sys.argv official python documentation here : sys.argv

argv[0] is the script name (it is operating system dependent whether this is a full pathname or not)

If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

Refer below code for using sys.argv in your code

                          

The python script is invoked without any arguments here, with below command :

                          

Code Output : As can be seen that the list has only one element which is the name of the script. This is because no other command line arguments were passed while invoking the python file.

                          

Now lets try to invoke the Python file with some arguments, command shown below:

                          

Code Output : As can be seen all arguments passed are now available in the form of a list that can now be processed using List methods.

                          

Using 'argparse'

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

Instead of having to manually set variables inside of the code, argparse can be used to add flexibility and reusability to your code by allowing user input values to be parsed and utilized.

Some of the features thate makes 'argparse' a great utility for handling arguments is :
  • Handles both Optional and Positional arguments.
  • Produces highly informative usage messages.
  • Supports parsers that dispatch to subparsers.

The 'argparse' module contains the 'ArgumentParser' public class which is the main entry point for command-line parsing.

The add_arguments( ) method is used to populate theparse with actions for optional and positional arguments.

The parse_args( ) method is invoked to convert the args of the command-line into an object with attributes.

Refer this below example code for parsing arguments using argparse :

                          

The above code is passed with below command line :

                          
NOTE : In the code, the argument has been specified to be referenced using both '-n' or '--name'. Both of them point to the same argument. User can choose either of them as they wish. The representation of the letter is more document and reader friendly. For example the below command is the same as the upper command. Using both commands will generate same results.
                          

Code Output :

                          
Using Help

'argparse' by default reserves the '-h' and '--help' keywords for help with the command line arguments.

It is always good to give a short description of what the argument means ans what value it expects.

'Help' for an argument can be specified at the time of adding the argument while calling the add_argument( ). One of the attributes of the add_argument( ) method is 'help' which takes input in the form of a string. This is where the user can specify a short description of the arguments usage and intent.

For example in above code we have specified a small help for the '--name' argument.

User can invoke the Python file with the '-h' or '--help' argument and the respective helps for all the arguments will be populated.

For example lets try running the below command for the above code :

                          

OR

                          

Code Output : As can be seen that the description provided for the argument '-n', '--name' appears when the help for the file is invoked.

                          
Optional Arguments

In a python script it might now always be the case that all the arguments specified using add_argument( ) are compulsorily required. Some can also be Optional while others are sitrictly required to be specified.

For example consider a situation where a python script does a lot of calculation and creates and deletes lots of log files in the process. Sometimes a user can require to actually look into the content of the log files created instead of them getting deleted. For such situations the user can add an optional argument to their script and pass it only when they require to have the logs dumped and not deleted.

To support this feature there is attribute 'required' to the add_argument( ) method. This attribute takes a boolean value as its input. If this attribute is set as 'True' the the argument is mandatory and always has to be passed, otherwise the script will exit with an Error. Keeping its value as 'False' categorizes the argument as optional and it can be ignored by the user or can be specified when required.

For example we have modified the above code and have added another argument which is kept to be optional.

Refer code below :

                          
                          

The below command line is used when trying to run the code. The second argument is ignored and not passed.

Code Output : As can be seen that there is no error, since the argument was optional.

                          
Argument Type

There is another attribute to the add_argument( ) method which is 'type'. This allows the user to decide the type the value of the argument will have

The argument values that python takes from the command line are string by default, but user can specify this value to be 'int'. By specifying the type as 'int' the value will be available as integer in the code.

For example refer below code. Here we will implement two arguments '--arg1' and '--arg2'. To both of these arguments we will pass integer values from the commandline. We will specify the type as 'int' for only '--arg2'.

                          

The following command line is passed :

                          

Code Output : As can be seen that the value corresponding to '--arg1' argument is string, whereas the value corresponding to '--arg2' is integer, since its type was specified as 'int' when the add_argument( ) method was called.

                          
Specifying Flags (Arguments without Values)

Many a times it is so required that an argument is specified as a 'flag'. What that means is that arguments sole purpose is to signify a True/False value, i.e. if that flag is passed the correspondint value is 'True' and if not the corresponding value is 'False'.

Obvioulsy this can be tackled by passing 'True' and 'False' value to a mandatory parameter, but this approach is too verbose and sometimes we need simplicity in out code.

The example above for generation of logs is the perfect use case for this. For such a scenario we do not need a value of the '-l' or the '--logs' argument. Just the argument being passed is sufficient enough to determine whether the action needs to be done or not.

add_argument( ) method has another attribute called 'action', whose value can be 'store_false', 'store_const' or 'store_true'.

When the value for 'action' is chosen as 'store_true' . there is no need to specify a value for its corresponding argument.

For example refer below code where the '-l' or '--logs' argument is specified as an optional flag.

                          

We run below command (not specifying the -l or --logs flag) :

                          

Code Output :

                          

Now, we run below command (Specifying the -l or --logs flag) :

                          

Code Output :

                          
Positional Arguments

There are times when we know what value to provide at what position and we don'y necessarily need an argument name to help with the command line.

For example consider a command line usage for a python code that has only two mandatory arguments, the users 'First Name' and the users 'Last Name'. For such a simple operations it would be rather unnecessary to specify argument names like --fname or --lname for these values. In such conditions just positionally specifying the values will do the trick.

Consider below code for specifying arguments positionally without using any argument names :

                          
                          

Code Output :

                          
Multiple Arguments

Sometimes ther are situations where there are more than one value to a particular argument.

For example consider the situation for specifying your full name. Many people do not have surnames or a middle name, whereas many people have long names that might not completely be described using just first name, middle name and last name. For such situations it would be required that the user provides multiple values for an argument.

add_argument( ) has another attribute called as 'nargs' which lets the user specify the number of values there will be for a particular argument.

User can specify a numerical value to this attribute and the exact same number of values will have to be passed to the argument from the command line.

Specifying value as '+' to the 'nargs' attribute allows the argument to have any number of values instead of fixed number of values.

This feature can be understood with the help of code below :

                          

Lets try running the code with below command :

                          

Code Output :

                          

Now, lets run the code again with below command where the name now has 4 words instead of previous 3:

                          

Code Output : As can be observed, multiple values can now be provided for '--name' argument and only 3 values have to be specified for the '--dob' argument.

                          
Specifying Groups

Another important feature of argparse is making specific groups that are Mutually Exclusive.

There are times that, depending on one argument, you want to restrict the use of another. This could be because the user should only need to use one of the arguments, or that the arguments conflict with each other.

The method add_mutually_exclusive_group() let’s us do exactly that.

For example consider we have the option of doing some operations, say Add , Subtract, Multiply but only one needs to be picked. This makes all these operations mutually exclusive. Two or more of these options cannot be specified on the command line at the same time.

Consider example below for creating a mutually exclusive group of agruments :

                          

Lets try to run the code with only one argument option : (Calling with --multiply)

                          

Code Output :

                          

Now lets try calling two of the mutually exclusive arguments together, using the below command (Here we have called the --multiple and the --add argument together) :

                          

Code Output : As we can see the code returns with an error.

                          
Using Subparsers

There are sometimes situations where we need a particular set of argument for a particular situation.

Lets try to see this as an example. For instance, the git command has may functions like : git add, git push, dit diff etc. For each of these operations there are a different set of arguments available which are only valid for that particular operation.

In a similar way 'argparse' allows the user to select/create a particular set of arguments for a particular operation indended. This is what is basically called as a subparser.

Using 'argparse', the user can create any number of subparsers.

Lets try to understand this through an example :

Consider the below three operations here :
  • Adding a User : Here we try to add a user and for this operation we take information like name (first name only) and used-id from arguments.
  • Taking Mail ID and Password : Here we will take the mai ID nad the password from the user in the form of arguments.
  • Age and Experience : Here we will take the age and relevant industry experience of the user (in years).

This is done using the add_subparser( ) method of the ArgumentParser( ).

Refer code below :

                          

Here we use below command to specify the operation as 'add_user' with is corresponding arguments :

                          

Code Output :

                          

Now we use below command to specify the operation as 'add_mail_pwd' with is corresponding arguments :

                          

Code Output :

                          

And finally we use below command to specify the operation as 'add_age_exp' with is corresponding arguments :

                          

Code Output :