Here is the source code for a python program called argv.py
import sys
# print the length of argv and all of the elements
print("The sys.argv list contains %d elements." % len(sys.argv))
print("The elements are:")
for i in range(len(sys.argv)):
print(" %d: %s" % (i, sys.argv[i]))
# extract the first argument after the program name
first = sys.argv[1]
print()
print("first argument after program name: %s" % (first))
Here are some sample runs of that program:
$ python3 argv.py hello
The sys.argv list contains 2 elements.
The elements are:
0: argv.py
1: hello
first argument after program name: hello
$ python3 argv.py this program has a lot of arguments
The sys.argv list contains 8 elements.
The elements are:
0: argv.py
1: this
2: program
3: has
4: a
5: lot
6: of
7: arguments
first argument after program name: this
$ python3 argv.py
The sys.argv list contains 1 elements.
The elements are:
0: argv.py
Traceback (most recent call last):
File "argv.py", line 10, in <module>
first = sys.argv[1]
~~~~~~~~^^^
IndexError: list index out of range
Notice in the last example that if we assume that the user types a command-line
argument, but they don’t, our program crashes. You can verify they typed
an argument by adding a simple check to make sure that the length of sys.argv
matches your expectations.