How to use command-line arguments in a Python console application

Command-line arguments or parameters are useful in many situations. In this post, I will give you examples of when and why to use them, as well as some examples.

The short answer is you can get all the command-line arguments using the following code.

import sys

if __name__ == '__main__':
    print(sys.argv)

Keep reading to find out when and why to use them.

Table of Contents

What is a command-line argument?

A command-line argument is closely related to console applications. Although they can also be used in graphical user interfaces applications.

For an example of a console application, you can read this post (it is a full example about how to create a multiplication table in a python console application).

As an example, if you are going to execute a python program from the source code, you should do it as follows:

Command-line arguments example
Command-line arguments example

You open a console/terminal (in windows you use the Windows Command Prompt, a.k.a. cmd), you write “python”, then a space, and last the python source code file that you want to execute. In this case, “main.py” is a command-line argument to the executable “python”.

Why do we use command-line arguments?

Command-line arguments are similar to function/method parameters.

When you need some input to do some operations and give an output, one of the ways to provide that input is by using command-line arguments.

Another situation that you can use command-line arguments is when you want to do something with a file. One example is to execute a python code, you write something like in the figure above “python main.py”. In this case, we pass as an argument the name of a file.

Capturing the command-line arguments: sys.argv

One of the ways we have in python to get the command-line arguments is using sys.argv.

This variable is a list. The first element is the name of the file, and from there the rest are the command-line arguments.

See the example below.

import sys

if __name__ == '__main__':
    length = len(sys.argv)
    print("Number of parameters: " + str(length) + "\n")
    
    print("Parameters: \n")
    for i in range(1,length):
        print(sys.argv[i]) 

If you execute a file (.py file) with the code above, and the command line-parameters 1 2 3, you will get the following result.

Command-line arguments example: four arguments
Command-line arguments example: four arguments

Example 1: Add two numbers using command-line arguments

In this case, we are going to create a program that gets two numbers as a command-line argument and print the sum on the screen.

import sys

if __name__ == '__main__':
    number1 = int(sys.argv[1])
    number2 = int(sys.argv[2])
    print("The sum is: ")
    print (number1+number2)

Notice that all the command-line parameters are passed as strings to our program. That is why we have to convert them to integers in this case.

What do you think will happen if you don’t give any argument?

You are right, an exception will occur. So, we are going to modify our code to give directions to the user on how he or she should use our program to sum two numbers. Find the code below.

import sys

if __name__ == '__main__':
    if (len(sys.argv)!=3):
        print ("Ussage: python main.py 4 5")
        print ("You should pass two numbers as command-line arguments to the console app. Please try again.")
        exit()
    number1 = int(sys.argv[1])
    number2 = int(sys.argv[2])
    print("The sum is: ")
    print (number1+number2)

As a result, you can get something like in the picture below.

Example of input validation for a console application with command-line arguments
Example of input validation for a console application with command-line arguments

Now you can ask, ok what will happen if the arguments are not numbers?

Again, an exception will occur. You can see how to handle exceptions in python in this post.

To practice

You can practice command-line arguments by modifying the code here.

That code is about printing the pascal triangle for a given number.

Now, you can give the number as a command-line argument.

Summary

Command-line arguments can be useful in many situations.

An important aspect to consider when using them is to have proper exception handling in place so the app won’t crash with any input, and you give useful informative messages to the user.

H@ppy coding!

Related posts: