How to use sys.argv in Python

Published on Aug. 22, 2023, 12:15 p.m.

To use sys.argv in Python, you first need to import the sys module. Then you can access the command-line arguments passed to the script as elements in the sys.argv list.

Here’s an example:

import sys

# Print the total number of command line arguments
print("Total arguments: ", len(sys.argv))

# Print the command line arguments
for i, arg in enumerate(sys.argv):
    print("Argument", i, ":", arg)

When this code is executed with the command python myscript.py arg1 arg2 arg3, the output will be:

Total arguments: 4
Argument 0: myscript.py
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3

As you can see, sys.argv[0] contains the name of the script itself, while subsequent elements contain the command-line arguments.

I hope this helps! Let me know if you have any further questions.

Tags:

sys