User Input and Error Handling
4.2 Reading from the Command Line
Programs running on Unix computers usually avoid asking the user questions. In- stead, input data are very often fetched from the command line. This section explains how we can access information on the command line in Python programs.
4.2.1 Providing Input on the Command Line
We look at the Celsius-Fahrenheit conversion program again. The idea now is to provide the Celsius input temperature as acommand-line argumentright after the program name. This means that we write the program name, herec2f_cml.py (cmlforcommand line), followed the Celsius temperature:
Terminal
c2f_cml.py 21 69.8
Inside the program we can fetch the text21assys.argv[1]. Thesysmodule has a listargvcontaining all the command-line arguments to the program, i.e., all the
“words” appearing after the program name when we run the program. In the present case there is only one argument and it is stored insys.argv[1]. The first element in thesys.argvlist,sys.argv[0], is always the name of the program.
A command-line argument is treated as a text, sosys.argv[1]refers to a string object, in this case’21’. Since we interpret the command-line argument as a num- ber and want to compute with it, it is necessary to explicitly convert the string to afloatobject. In the program we therefore write
152 4 User Input and Error Handling
import sys
C = float(sys.argv[1]) F = 9.0*C/5 + 32 print F
As another example, consider the program
v0 = 5 g = 9.81 t = 0.6
y = v0*t - 0.5*g*t**2 print y
for computing the formulay.t/Dv0t12gt2. Instead of hardcoding the values of v0andtin the program we can read the two values from the command line:
Terminal
ball2_cml.py 0.6 5 1.2342
The two command-line arguments are now available assys.argv[1]andsys.
argv[2]. The completeball2_cml.pyprogram thus takes the form
import sys
t = float(sys.argv[1]) v0 = float(sys.argv[2]) g = 9.81
y = v0*t - 0.5*g*t**2 print y
4.2.2 A Variable Number of Command-Line Arguments
Let us make a programaddall.pythat adds all its command-line arguments. That is, we may run something like
Terminal
addall.py 1 3 5 -9.9
The sum of 1 3 5 -9.9 is -0.9
The command-line arguments are stored in the sublistsys.argv[1:]. Each ele- ment is a string so we must perform a conversion tofloatbefore performing the addition. There are many ways to write this program. Let us start with version 1, addall_v1.py:
import sys s = 0
for arg in sys.argv[1:]:
number = float(arg) s += number
print ’The sum of ’, for arg in sys.argv[1:]:
print arg, print ’is ’, s
The output is on one line, but built of severalprintstatements with a comma at the end to prevent the usual newline character thatprintotherwise adds to the text.
The command-line arguments must be converted to numbers in the firstforloop because we need to compute with them, but in the second loop we only need to print them and then the string representation is appropriate.
The program above can be written more compactly if desired:
import sys
s = sum([float(x) for x in sys.argv[1:]])
print ’The sum of %s is %s’ % (’ ’.join(sys.argv[1:]), s)
Here, we convert the listsys.argv[1:]to a list offloatobjects and then pass this list to Python’ssumfunction for adding the numbers. The constructionS.join(L) places all the elements in the listLafter each other with the stringSin between.
The result here is a string with all the elements insys.argv[1:] and a space in between, which is the text that originally appeared on the command line.
4.2.3 More on Command-Line Arguments
Unix commands make heavy use of command-line arguments. For example, when you writels -s -tto list the files in the current folder, you run the programls with two command-line arguments:-sand-t. The former specifies thatlsis to print the file name together with the size of the file, and the latter sorts the list of files according to their dates of last modification. Similarly, cp -r my new for copying a folder treemyto a new folder treenewinvokes thecpprogram with three command line arguments: -r(for recursive copying of files),my, andnew. Most programming languages have support for extracting the command-line arguments given to a program.
An important rule is that command-line arguments are separated by blanks.
What if we want to provide a text containing blanks as command-line argument?
The text containing blanks must then appear inside single or double quotes. Let us demonstrate this with a program that simply prints the command-line arguments:
import sys, pprint
pprint.pprint(sys.argv[1:])
154 4 User Input and Error Handling
Say this program is namedprint_cml.py. The execution
Terminal
print_cml.py 21 a string with blanks 31.3 [’21’, ’a’, ’string’, ’with’, ’blanks’, ’31.3’]
demonstrates that each word on the command line becomes an element insys.argv. Enclosing strings in quotes, as in
Terminal
print_cml.py 21 "a string with blanks" 31.3 [’21’, ’a string with blanks’, ’31.3’]
shows that the text inside the quotes becomes a single command line argument.