How to Use sys.argv in Python



In this article, you will learn how to use sys.argv in Python.

How to use sys.argv

sys.argv is a list in Python that contains the command-line arguments passed to a Python script. The first item in the list sys.argv[0] is the name of the script itself, and the rest of the items are any arguments passed to the script. Here’s an example of how to use sys.argv:

import sys

# Print the number of arguments

# Print the arguments
for arg in sys.argv:

If you save this code as a file named and run it with the command python arg1 arg2 arg3, you’ll see the following output:


In this example, sys.argv is used to print the number of arguments passed to the script and to print each argument. You can use sys.argv to parse command-line arguments and perform different actions based on the arguments passed to the script. For example, you could write a script that performs different operations based on a command-line argument:

import sys

if len(sys.argv) < 2:
    print("Usage: python [operation]")

operation = sys.argv[1]

if operation == "add":
    print(int(sys.argv[2]) + int(sys.argv[3]))
elif operation == "subtract":
    print(int(sys.argv[2]) - int(sys.argv[3]))
    print("Invalid operation")

In this example, the script checks for the presence of a command-line argument, which should be the name of an operation to perform. If the argument is "add", the script adds the next two arguments and prints the result. If the argument is "subtract", the script subtracts the third argument from the second argument and prints the result. If the argument is anything else, the script prints an error message. You could run this script with the command python add 2 3 to print the result of adding 2 and 3.