Command Line Arguments
This page is under construction. Please come back later.
When running programs from the command line we have the option of supplying additional information in the form of arguments on the command line. Command line arguments take the form of strings separated by spaces. For example the following command line program invokation has three additional arguments.
$ python Program.py Fred 123 Flintstone
In our programs we can access each of these arguments using the variables
sys.argv[0]
, sys.argv[1]
, sys.argv[2]
, etc.
The program name can be found in the variable with the 0 subscript. The user supplied arguments are in the variables with subscripts 1, 2, 3, etc.
#!/usr/bin/env python3; import Utils import sys # Begin Main print("Number of arguments: " + str((len(sys.argv) - 1))) print("Program Name: " + sys.argv[0]) print("Arg 1: " + sys.argv[1]) print("Arg 2: " + sys.argv[2]) print("Arg 3: " + sys.argv[3]) print("Arg 4: " + sys.argv[4])
Output
Be sure to include the import sys
line in your program in order to be able to access the sys.argv
variables.
If we want to treat a command line argument as a number we first need to convert from the string representation passed on the command line to a numeric type. This is where conversion functions come in handy. The example below illustrates how to convert command line arguments to integers.
#!/usr/bin/env python3; import Utils import sys # Begin Main a = Utils.stoiWithDefault(sys.argv[1], 0) b = Utils.stoiWithDefault(sys.argv[2], 0) c = a + b print("{0:d} + {1:d} = {2:d}".format(a, b, c))
Output
The example below converts the command line arguments to floating point values.
#!/usr/bin/env python3; import Utils import sys # Begin Main a = Utils.stodWithDefault(sys.argv[1], 0) b = Utils.stodWithDefault(sys.argv[2], 0) c = a + b print("{0:f} + {1:f} = {2:f}".format(a, b, c))
Output
Questions
- {{Who's on first?}}
- {{Who's on second?}}
- {{Who's on third?}}
Projects
More ★'s indicate higher difficulty level.
- Combined FICA Tax (Command Line Argument)
- Cubic Roots (Command Line)
- Dog Years (Command Line)
- Milky Way Stellar Density Estimate
- Quadratic Roots (Command Line)
References
- [[Python Language Reference]]
- [[Python Standard Library]]
- [[Python at TutorialsPoint]]