How to Use Command-Line Arguments in Python

Command-line arguments are an essential aspect of programming, particularly when it comes to automating tasks and handling batch processing.

The command-line arguments in Python are passed during the execution of the script. Understanding how to use this aspect of Python can vastly improve your efficiency and versatility as a programmer.

There is a special type of variable, known as sys.argv, which is a list in Python that consists of the command-line arguments that were passed. In this tutorial, we will learn how to use command-line arguments in Python.

Step 1: Import the Sys Module

To use command-line arguments in Python, one of Python’s built-in modules named sys needs to be imported.

Step 2: Using sys.argv

Once imported, we can use the argv in the sys module. Argv stands for ‘argument value.’ It’s a list in Python, which contains the command-line arguments passed to the script. In the list sys.argv, the first index (sys.argv[0]) is always reserved for the script name (the name of the running program). From there, sys.argv[1] would be the first argument, sys.argv[2] the second, and so on.

It should be noted that all arguments passed to sys.argv are parsed as strings.

Step 3: Example of Using sys.argv

As an example, let’s say we have a script named script.py that we run with two arguments, like so:

The list sys.argv would then look like this:

'script.py', 'argument1', 'argument2'

Step 4: Handling Errors

Trying to access an argument that was not passed would yield an index out-of-range error. A useful approach to handling such situations is checking the length of the sys.argv list before accessing its elements. The len() function in Python can be used for this purpose.

Full Code

Let’s suppose we have written a script, script.py, which receives two numbers as command-line arguments and prints their sum.

We can execute this script as follows:

And the output will be:

Sum: 30

Conclusion

Understanding command-line arguments is a critical skill in Python programming. It allows your scripts to interact with the outside environment, take in input in a flexible way, and can greatly improve the versatility of your programs. We hope this tutorial has provided some clarity on how to use command-line arguments in Python!