Pythonic arguments
We should know by now that we will want to be able to pass command-line arguments to Python and we can do this using the argv
array similar to Perl. However, we are more like bash, with Python we combine the program name into the array with the other arguments. Python also uses lowercase instead of uppercase in the object name.
The
argv
array is a part of thesys
objectsys.argv[0]
is the script namesys.argv[1]
is the first argument supplied to the scriptsys.argv[2]
is the second supplied argument and so onThe argument count will always be at least 1, so, keep this in mind when checking for supplied arguments
Supplying arguments
If we create the $HOME/bin/args.py
file we can see this in action. The file should be created as follows and made executable:
#!/usr/bin/python3 import sys print("Hello " + sys.argv[1])
If we run the script with a supplied argument, we should be able to see something similar to the following screenshot:
Our code is still quite clean and simple; however...