COMMAND-LINE ARGUMENTS
Python provides a getopt module to parse command-line options and arguments, and the sys module provides access to any command-line arguments via the sys.argv. This serves two purposes:
sys.argvis the list of command-line arguments.len(sys.argv)is the number of command-line arguments.
Here, sys.argv[0] is the program name, so if the program is called test.py, it matches the value of sys.argv[0].
Now you can provide input values for a Python program on the command line instead of providing input values by prompting users for their input.
As an example, consider the script test.py shown here:
#!/usr/bin/python
import sys
print('Number of arguments:',len(sys.argv),'arguments')
print('Argument List:', str(sys.argv))
Now run above script as follows:
python test.py arg1 arg2 arg3
This will produce following result:
Number of arguments: 4 arguments. Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
The ability to specify input values from the command line provides useful functionality. For example, suppose that you have a custom Python class that contains the methods add and subtract to add and subtract a pair of numbers.
You can use command-line arguments to specify which method to execute on a pair of numbers, as shown here:
python MyClass add 3 5 python MyClass subtract 3 5
This functionality is very useful because you can programmatically execute different methods in a Python class, which means that you can write unit tests for your code as well. Read Chapter 8 to learn how to create custom classes.
Listing 1.14 displays the content of hello.py that shows you how to use sys.argv to check the number of command line parameters.
LISTING 1.14: hello.py
import sys
def main():
if len(sys.argv) >= 2:
name = sys.argv[1]
else:
name = 'World'
print('Hello', name)
# Standard boilerplate to invoke the main() function
if __name__ == '__main__':
main()
Listing 1.14 defines the main() function that checks the number of command-line parameters: if this value is at least 2, then the variable name is assigned the value of the second parameter (the first parameter is hello.py), otherwise name is assigned the value Hello. The print() statement then prints the value of the variable name.
The final portion of Listing 1.14 uses conditional logic to determine whether to execute the main() function.