5.8. A Python program

Here is the Python program hello.py first discussed in hello_world. If you didn’t do it the first time we discussed this program, you should now download it and put it in a file called hello.py.

As discussed in that section, the file hello.py is a Python file that contains an extremely simple Python program. In this section we discuss what makes it a script, that is, a Python program that can be run from the command line by connecting the directory in which you saved hello.py and typing:

$ python hello.py

(the $ is my commandline prompt; the rest is what I typed on my keyboard, followed by <Enter>). If Python is running and you call the program this way, it prints:

Hello World

The following is what the file contains:

 1import sys
 2
 3def main():
 4   """
 5   Get the name from the command line, using 'World' as a fallback.
 6   """
 7   if len(sys.argv) >= 2:
 8     name = sys.argv[1]
 9   else:
10     name = 'World'
11   print ('Hello', name)
12
13if __name__ == '__main__':
14   main()

Consider the somewhat mysterious looking last two lines. What exactly do they do?

To answer this question, let’s delete the last two lines of the program, and save the result in a new file truncated_hello.py. Now run this new truncated file from the commandline just as you ran hello.py:

$ python truncated_hello.py

What happens? What happens is that the program now does nothing. No hello. So those two lines were pretty important.

One more experiment. Try just typing python to bring up the Python prompt. Next import hello.py. Still nothing happens. Now try running the program just as in the last line of hello.py:

>>> import hello
>>> hello.main()
Hello, World

The Hello, World came back.

So what happened?

What happens when you import a file or just call it with Python as in:

$ python hello.py

is that every instruction in the program gets executed. In the case of hello.py, that includes all the function definitions and the if statement at the end of the file:

if __name__ == '__main__':
     main()

As with any if statement, the second line of the if statement is not run if the condition on the first line is not met. The condition __name__ == '__main__' is True only if hello.py is being called on the Python commandline. When hello.py is imported it is false. Thus the last line of the file only gets executed when hello.py is being called on the Python commandline (which we will refer to as using hello.py as a script).

In both importing and executing from the commandline all of the file is executed, but the value of __name__ is different in the two cases, and different things happen when the file is loaded.

The bottom line: if you want to define a set of instructions to be executed when the file is run as a script (from the commandline), indent them under an:

if ___name__ == '__main__':

test.