Python 3home |
Introduction to Python
davidbpython.com
sys.argv is a list that holds string arguments entered at the command line
a python script get_args.py
import sys # import the sys library
print('first arg: ' + sys.argv[1]) # print first command line arg
print('second arg: ' + sys.argv[2]) # print second command line arg
running the script from the command line, with two arguments
$ python myscript.py hello there first arg: hello second arg: there
sys.argv[0] will always contain the name of our program.
a python script print_args.py
import sys
print(sys.argv)
(passing 3 arguments)
$ python print_args.py hello there budgie ['myscript2.py', 'hello', 'there', 'budgie']
running the script from the command line (passing no arguments)
$ python print_args.py ['myscript2.py']
Since we read arguments from a list, we can trigger an IndexError if we try to read an argument that wasn't passed.
a python script addtwo.py
import sys
firstint = int(sys.argv[1])
secondint = int(sys.argv[2])
mysum = firstint + secondint
print(f'the sum of the two values is {mysum}')
passing 2 arguments
$ python addtwo.py 5 10 the sum of the two values is 15
passing no arguments
$ python addtwo.py Traceback (most recent call last): File "addtwo.py", line 3, in <module> firstint = int(sys.argv[1]) IndexError: list index out of range
How to handle this exception? Test the len() of sys.argv, or trap the exception.