CLI arguments allow us to provide arguments into a program while calling them from the command-line itself, rather than having to ask for input from within the program.

SYS

argv

The sys module gives us functionality related to the system running the program, including argv to create command-line arguments:

import sys
 
print("hello, my name is", sys.argv[1])

Note that the call to the argv list us using index 1, because the 0th index position is taken by the name of the script itself (or whatever is passed immediately after the call to the Python program).

(Trivia: argv stands for argument vector, which is a list of all command-line arguments passed when calling the program).

Note that care must be taken to ensure that we do not create IndexErrors by calling, for instance, sys.argv[1] without providing an argument after the name of the program.

exit

Instead of using try...except blocks we can write more defensive code with sys.exit, which can allow us to exit the program if a condition is met:

import sys
 
if len(sys.argv) < 2:
	sys.exit("Too few arguments")
 
print("My name is", sys.argv[1])