[Tutor] Runing a Python program
Kent Johnson
kent37 at tds.net
Sat May 13 14:51:57 CEST 2006
Henry Dominik wrote:
> Hello people,
>
> 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
To be able to import a module, the directory containing the module must
be in sys.path. sys.path is just a list of directory paths. The Python
runtime searches each of these directories for your module.
So one thing you can do is make sure your module is in a directory that
is in sys.path. A couple of possibilities are the current working
directory and the site-packages directory.
On my computer (Win2K) Python puts the current working directory in
sys.path. (I'm not sure this happens on Linux.) You can see this if you
print sys.path; it is the empty string that starts the list. So I often
cd to the directory containing a program before starting Python. Then I
can import modules from that directory.
For modules you want to be able to use from several programs, you can
put them in C:\Python24\Lib\site-packages. This directory is always
added to sys.path and it is intended as a place to install extra modules
and packages. Most third-party modules will install to site-packages.
Alternately you can modify sys.path to include the dir you want. There
are several ways to do this. One way, as Evans showed, is to change it
at runtime by appending a new path. This is fine for temporary changes
but not very convenient in the long run. Another possibility is to edit
the environment variable PYTHONPATH and add your dir to it. You can also
create a .pth file in site-packages that contains the path to the dir to
add to sys.path.
You can find more info here:
http://docs.python.org/tut/node8.html#SECTION008110000000000000000
http://docs.python.org/lib/module-site.html
Kent
More information about the Tutor
mailing list