[mod_python] module import

Graham Dumpleton grahamd at dscpl.com.au
Mon Jan 24 18:06:11 EST 2005


Lionel Roubeyrie wrote ..
> Hi all,
> new in the mod_python's world, I'm starting with a little problem of import.
> The index.py page must import a package in the subdirectory where index.py
> is, 
> then I wrote:
> import os, sys
> current_path = os.getcwd()
> top = os.path.join(current_path, '../')
> if top not in sys.path : sys.path.append(top)
> import my_mod
> 
> mod_python raise an error, but puting the lines in a python shell works!
> Do I have to do anything else?

The value returned by os.getcwd() will be '/' and not the directory in which
the index.py resides. It is also not a good idea to be modifying sys.path
the way you are.

One option is to use the PythonPath directive to add additional directories
to search for Python modules and then just use "import" without any of
the other stuff.

You don't say whether you are using mod_python.publisher or whether
your index.py is listed as PythonHandler directly, which makes it a bit harder
to guess behaviour, but in various cases the directory in which the content
handler resides will be listed in sys.path anyway.

One final alternative to modifying PythonPath is to use:

  import os
  from mod_python import apache

  directory = os.path.dirname(__file__)
  my_mod = apache.import_module("my_mod",path=[directory])

At least I think that will work. :-)

Graham


More information about the Mod_python mailing list