How to get the command line arguments in Python?

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

To get the command line arguments in Python, you can use the sys module. The sys.argv variable is a list in Python that contains the command-line arguments passed to the script. It can be indexed to access specific command-line arguments. Here’s an example:

import sys

# Get the command-line arguments
args = sys.argv

# Print the number of command-line arguments
print(f"Number of arguments: {len(args)}")

# Print each command-line argument
for arg in args:
    print(arg)

In this example, we import the sys module and then use sys.argv to get the command-line arguments. We print the number of arguments using the len() function, and then use a for loop to print each command-line argument.

Note that the first item in sys.argv is always the name of the script itself, so the actual command-line arguments start at index 1. If you need to access specific command-line arguments, you can do so by indexing into sys.argv, like this: sys.argv[1] for the first argument, sys.argv[2] for the second argument, and so on.

It’s worth noting that this method of parsing command-line arguments is not very flexible or robust. For more advanced command-line argument parsing, you may want to consider using the argparse module, which provides a more feature-rich way of parsing command-line arguments.