Making Scripts More Robust
What happens if you run the greet.py script from the previous step without providing a name? Let's try it.
python greet.py
You will encounter an error.
Traceback (most recent call last):
File "/home/labex/project/greet.py", line 4, in <module>
name = sys.argv[1]
IndexError: list index out of range
This IndexError occurs because the script tries to access sys.argv[1], but since no argument was provided, this index does not exist. A robust script should handle such cases gracefully.
Let's modify greet.py to check if an argument was provided. If not, it will use a default name. We can check the number of items in the sys.argv list using the len() function. If len(sys.argv) is greater than 1, it means at least one argument was provided.
Update your greet.py file with the following code:
import sys
if len(sys.argv) > 1:
## Use the provided argument if it exists
name = sys.argv[1]
else:
## Use a default name if no argument is provided
name = "World"
print(f"Hello, {name}!")
Now, your script is more robust. Run it again without an argument:
python greet.py
This time, it runs without error and uses the default name.
Hello, World!
And it still works correctly when you provide an argument:
python greet.py LabEx
Hello, LabEx!
Handling potential errors and providing default behaviors are key practices for writing reliable command-line applications.