[Tutor] Runing a Python program
Alan Gauld
alan.gauld at freenet.co.uk
Sat May 13 15:58:50 CEST 2006
Hi Henry,
> As a new python programmer, I created a directory in
> 'C:\python24\myPythonFiles', and added a simple python
> under the myPythonFiles directory; but when I tried
> running it on the Python Shell, I got the following error.
>
>>> import myPythonFiles.readOut
> ImportError: No module named myPythonFiles.readOut
Ok, the first thing to say is that you are not running the
program but importing it, there is a difference.
To run a Python program in Windows either double click it
in Windows Explorer (it should have a snake icon to show
that the association is set up correctly) or at a DOS
command prompt (or the Start->Run dialog) type
C:\> python C:\python24\myPythonFiles\readOut.py
In either case you may find the program runs so fast you
can't see the output. In that case add a final line like:
raw_input("Hit ENTER to quit")
When you import a module it does indeed execute
the code in that module and so might appear to run
the program, but there is one important distinction
(which you may not have come across yet!) You can
put a clause into the module like:
if __name__ == "__main__":
# some code here
and the code under the if will only be executed when the
file is run as a program, it will NOT be executed when
the file is imported as a module. (This is a powerful feature
that greatly eases the task of writing reusable code
in Python.)
Now the second thing to note is that your import syntax
is wrong.
To make the files in your directory visible toi the import
command you need to modify the value in sys.path.
There are a number of ways to do this, the one that I
use is to create a PYTHONPATH environment variable
(MyComputer->Properties->Advanced->Environment Variables)
which points to all the folders where I keep Python code,
in the same way that the DOS PATH variable points to
my executable files.
HTH,
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list