9. Executing a program

Create your work directory e.g. class_files and cd to it. Fire up your editor and save this text as hello_world.py

print "hello world!"

9.1. Executing Python in unix/Mac/cygwin

Make the file executable.

chmod 755 hello_world.py

At the command prompt, run it

# python hello_world.py
hello world!

Congratulations, you are now officially a computer programmer.

The above command works because python will have been installed in your $PATH.

You can invoke the interpreter from within your program using the shebang convention. Here's the new code (the "#!" is called a shebang)

#! /usr/bin/python 
print "hello world!"

You run it from the command line like this

# ./hello_world.py
hello world!

9.2. Executing Python in Windows

In windows you'll be in a command box at \Documents and Settings\UserName\class_files (or \My Documents\class_files which is the same thing). The python install sets up the registry so that you can directly execute the python program. You only need to do

hello_world.py

Congratulations, you are now officially a computer programmer.

You can execute the program by clicking on the filename using windows explorer, but the output window will open and close too fast for you to see what happened.

The unix execution options are still available, but you don't need them in windows

  • Direct execution

    #python not in the PATH
    "\Program Files"\Python25\python hello_world.py
    

    To add python to the PATH see How to set the PATH in windows (http://www.computerhope.com/issues/ch000549.htm). After doing this you can type python rather than "\Program Files"\Python25\python

    #python in the PATH
    python hello_world.py
    
  • The shebang convention

    • hello_world.py for python not in the PATH

      #! c:"\Program Files"\Python25\python
      print "hello world!"
      
    • hello_world.py for python in the PATH

      #! python
      print "hello world!"
      

    executing the program

    hello_world.py