How to Use sys.argv in Python

09/14/2021

Contents

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(len(sys.argv))

# Print the arguments
for arg in sys.argv:
    print(arg)

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

4
script.py
arg1
arg2
arg3

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 script.py [operation]")
    sys.exit()

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]))
else:
    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 script.py add 2 3 to print the result of adding 2 and 3.