On line 1 we have what’s called an “import.” This is how you add features to your script from the Python feature set. Rather than give you all the features at once, Python asks you to say what you plan to use. This keeps your programs small, but it also acts as documentation for other programmers who read your code later.
The argv is the “argument variable,” a very standard name in programming that you will find used in many other languages. This variable holds the arguments you pass to your Python script when you run it. In the exercises you will get to play with this more and see what happens.
Line 3 “unpacks” argv so that, rather than holding all the arguments, it gets assigned to four variables you can work with: script, first, second, and third. This may look strange, but “unpack” is probably the best word to describe what it does. It just says, “Take whatever is in argv, unpack it, and assign it to all these variables on the left in order.”
Notice though that we make a variable prompt that is set to the prompt we want, and we give that to raw_input instead of typing it over and over. Now if we want to make the prompt something else, we just change it in this one spot and rerun the script.
A few fancy things are going on in this file, so let’s break it down real quick:
Lines 1–3 should be a familiar use of argv to get a filename. Next we have line 5 where we use a new command open. Right now, run pydoc open and read the instructions. Notice how like your own scripts and raw_input, it takes a parameter and returns a value you can set to your own variable. You just opened a file.
Line 7 we print a little line, but on line 8 we have something very new and exciting. We call a function on txt. What you got back from open is a file, and it’s also got commands you can give it. You give a file a command by using the . (dot or period), the name of the command, and parameters. Just like with open and raw_input. The difference is that when you say txt.read() you are saying, “Hey txt! Do your read command with no parameters!”
6 print "If you don't want that, hit CTRL-C (^C)."
7 print "If you do want that, hit RETURN."
8
9 raw_input("?")
10
11 print "Opening the file..."
12 target = open(filename, 'w')
13
14 print "Truncating the file. Goodbye!"
15 target.truncate()
16
17 print "Now I'm going to ask you for three lines."
18
19 line1 = raw_input("line 1: ")
20 line2 = raw_input("line 2: ")
21 line3 = raw_input("line 3: ")
22
23 print "I'm going to write these to the file."
24
25 target.write(line1)
26 target.write("\n")
27 target.write(line2)
28 target.write("\n")
29 target.write(line3)
30 target.write("\n")
31
32 print "And finally, we close it."
33 target.close()
That’s a large file—probably the largest you have typed in. So go slow, do your checks, and make it run. One trick is to get bits of it running at a time. Get lines 1–8 running, then five more, then a few more, and so on, until it’s all done and running.
6 print "Copying from %s to %s" % (from_file, to_file)
7
8 # we could do these two on one line too, how?
9 in_file = open(from_file)
10 indata = in_file.read()
11
12 print "The input file is %d bytes long" % len(indata)
13
14 print "Does the output file exist? %r" % exists(to_file)
15 print "Ready, hit RETURN to continue, CTRL-C to abort."
16 raw_input()
17
18 out_file = open(to_file, 'w')
19 out_file.write(indata)
20
21 print "Alright, all done."
22
23 out_file.close()
24 in_file.close()
You should immediately notice that we import another handy command named exists. This returns True if a file exists, based on its name in a string as an argument. It returns False if not.
6 # ok, that *args is actually pointless, we can just do this
7 def print_two_again(arg1, arg2):
8 print "arg1: %r, arg2: %r" % (arg1, arg2)
9
10 # this just takes one argument
11 def print_one(arg1):
12 print "arg1: %r" % arg1
13
14 # this one takes no arguments
15 def print_none():
16 print "I got nothin'."
17
18
19 print_two("Zed","Shaw")
20 print_two_again("Zed","Shaw")
21 print_one("First!")
22 print_none()
Let’s break down the first function, print_two, which is the most similar to what you already know from making scripts:
1. First we tell Python we want to make a function using def for “define.”
2. On the same line as def, we then give the function a name. In this case, we just called it print_two, but it could be peanuts too. It doesn’t matter, except that your function should have a short name that says what it does.
3. Then we tell it we want *args (asterisk args), which is a lot like your argv parameter but for functions. This has to go inside () parentheses to work.
4. Then we end this line with a : colon and start indenting.
5. After the colon all the lines that are indented four spaces will become attached to this name, print_two. Our first indented line is one that unpacks the arguments the same as with your scripts.
6. To demonstrate how it works, we print these arguments out, just like we would in a script.
Now, the problem with print_two is that it’s not the easiest way to make a function. In Python we can skip the whole unpacking args and just use the names we want right inside (). That’s what print_two_again does.
After that, you have an example of how you make a function that takes one argument in print_one.
Finally you have a function that has no arguments in print_none.
This shows all the different ways we’re able to give our function cheese_and_crackers the values it needs to print them. We can give it straight numbers. We can give it variables. We can give it math. We can even combine math and variables.
In a way, the arguments to a function are kind of like our = character when we make a variable. In fact, if you can use = to name something, you can usually pass it to a function as an argument.