Beginner

The command line is a big part of using and understanding programming in Python. In this article, we will cover the command line parameters argv and argc – their origin and how you can use them.

Command line parameters or arguments are a way to externally input data into your program(script) while it is executing – at runtime. This is achieved by providing the script name and parameters to be inputted. We will look at this in-depth later in this article.

Python command line arguments are inherited from the C programming language – that is where argv and argc originate from.

A lot of you would be familiar with how command line parameters work in C. Below is one such example:

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Arguments count: %d\n", argc);

    for (int i = 0; i < argc; i++) {
        printf("Argument %6d: %s\n", i, argv[i]);
    }
    return 0;
}

In the code above, main()defines the execution point of the C program. It has the parameters:

  • argc – the number of arguments in the program
  • argv – an array with the name of the program as the first element followed by any additional arguments that may have been passed.

Running the code we get this output:

NOTE: argc stands for argument count, while argv stands for argument vector.  

Command Line Parameters in Python

To use argv in Python, you have to first import the sys module that comes built into Python. After import, it would be accessed with the sys.argv command.

The next question would be what is sys.argv? Let’s have a look at that, shall we? Consider the code below:

import sys

print(sys.argv)
print(type(sys.argv))

Here is what happened:

  • The first line imports the sys module
  • The third line prints out the value of sys.argv
  • The fourth line prints out the type of sys.argv

When we run this program in the command line with python <filename> we get the following output:

The output of sys.argv is the name of the file back in list format. We also see that the type of sys.argv is a list.

Now we will rewrite the code that was shown in C but in Python this time:

import sys

if __name__ == '__main__':
    print(f"Arguments count: {len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument {i:>6}: {arg}")

NOTE: f-strings provide a way to embed expressions inside string literals, using a minimal syntax.

After running this program: python <filename> we see that the output we get is the same as the C program:

Taking a closer look we see that have one argument and that argument is the file itself.

Python does not have an argc variable because sys.argv is more than sufficient. If we wanted to get the number of parameters we can call the len() function as illustrated above.

Adding Parameters to sys.argv

I mentioned earlier that command line parameters are accomplished by giving the script name and parameters to be inputted: <script name> <parameter 1> <parameter 2>

Let’s add some parameters to the previous program. We are not changing anything in the code just adding arguments when we invoke it.

python <filename> Python Command Line Arguments

Each of the parameters is outputted as an element of the sys.argv list. Given that, you can specify what you want to be displayed from the list, and list operations can be performed on it.

import sys

print(f'Name of the script: {sys.argv[0]=}')
print(f'Arguments of the script: {sys.argv[1:]=}')

This is how the code works after import of the sys module:

  • The third line accesses the first element of the list – the name of the script – and extracts it.
  • The fourth line outputs the remaining elements of the list – these are the command line arguments.

About now, you may be asking what is the point of all this? Let’s take a look at some ways we can use sys.argv

How to Use sys.argv

As stated prior, command line arguments like sys.argv allow the input of data into a script externally. We do this because sometimes we do not want to hard code data to our program. sys.argv simplifies the user input process. For example, a simple calculator in Python would look something like this:

# Python program for simple calculator 

# Function to add two numbers 
def add(num1, num2): 
	return num1 + num2 

# Function to subtract two numbers 
def subtract(num1, num2): 
	return num1 - num2 

# Function to multiply two numbers 
def multiply(num1, num2): 
	return num1 * num2 

# Function to divide two numbers 
def divide(num1, num2): 
	return num1 / num2 

print("Please select operation -\n" 
		"1. Add\n" 
		"2. Subtract\n"  
		"3. Multiply\n"  
		"4. Divide\n") 

# Take input from the user 
select = int(input("Select operations form 1, 2, 3, 4 :")) 

number_1 = int(input("Enter first number: ")) 
number_2 = int(input("Enter second number: ")) 

if select == 1: 
	print(number_1, "+", number_2, "=", add(number_1, number_2)) 

elif select == 2: 
	print(number_1, "-", number_2, "=", subtract(number_1, number_2)) 

elif select == 3: 
	print(number_1, "*", number_2, "=", multiply(number_1, number_2)) 

elif select == 4: 
	print(number_1, "/", number_2, "=", divide(number_1, number_2)) 
    
else: 
	print("Invalid input") 

The code consists of four fuctions, each performing a different mathematical operation. A function is called based on a choice made by the user.

The issue, as we see in the output, is that the program asks for user input multiple times. This has the possibility of leading to input errors.

We could eliminate the number of inputs the user has to enter by allowing them to input all of the required data all at once:

import sys 

def main():
    if len(sys.argv) == 4:
        if sys.argv[1] == 'add':
            print(int(sys.argv[2]) + int(sys.argv[3]))
        elif sys.argv[1] == 'sub': 
            print (int(sys.argv[2]) - int(sys.argv[3])) 
        elif sys.argv[1] == 'mult': 
            print (int(sys.argv[2]) * int(sys.argv[3])) 
        elif sys.argv[1] == 'div': 
            print (int(sys.argv[2]) / int(sys.argv[3])) 
        else:
            print("INVALID ARGUMENTS")

if __name__ == '__main__': 
	main()       

This program:

  • Checks if the length of sys.argv is equal to 4
  • Based on what is inputted in the second list element ( sys.argv[1] ), it performs the operation corresponding to that input on the third ( sys.argv[2] ) and fourth ( sys.argv[3] ) elements
  • Ending by outputting that result

We get the same result but with only one user input. Let’s have a look at another example:

import sys 

add = 0.0

# Getting the length of command line arguments 
num = len(sys.argv) 

for i in range(1, num): 
	add += float(sys.argv[i]) 

print ("the sum is :", add) 

In this program:

  • An initial variable of add is declared and assigned the value 0.0
  • The length of sys.argv is stored in another variable
  • We iterate over the values from 1 to the length of sys.argv incrementing each value to add
  • The new value of add is then output.

By using the length of sys.argv this program is able to add every argument inputted regardless of their number.

These are some of the ways you can utilise command line parameters in Python.

Subscribe to our newsletter

Error SendFox Connection: 403 Forbidden

403 Forbidden