kseehof at neuralintegrator.com
Wed Nov 28 01:23:55 CET 2001
Fernando Pérez <fperez528 at yahoo.com> wrote:
> Ken Seehof wrote:
> > Why is the __file__ attribute (of a module) a relative filename rather
> > a fully qualified filename? One would think that the __file__ attribute
> > might be used for the purpose of locating and opening a source file,
> > If somebody wants a relative filename couldn't they split it
> > By making module.__file__ relative, information is lost. What was Guido
> > thinking??? Perhaps a __fullpath__ should be added.
> > Don't tell me about the fact that .pyc files might be moved along with
> > file from a different computer, thereby rendering the full pathnames
> > incorrect. That's a silly argument not worth addressing. :-)
> > Is there a good general way to determine the full pathname of a module
> > or is the best approach to search sys.path for module.__file__?
> I don't know what Guido was thinking, my telepathy cap broke yesterday.
> as far as finding full, correct pathnames, use the inspect module
> with python >=2.1). It can get you filenames, code, function headers, just
> about anything you want about an object.
> An example:
> In : ranlib ?
> Details for: ranlib
> Type: module
> String Form: <module 'ranlib' from
> Namespace: Local - IPython Session
> File: /usr/lib/python2.1/site-packages/Numeric/ranlib.so
Cool, that is a big help. Thanks. Ka-Ping Yee comes up with some neat
> > If the module is an extension module, how do I find the full pathname of
> > source code file (preferably platform independent)?
> You can't. It may have been compiled to binary and the source may not even
> on your computer at all. So it's inherently impossible to get it.
In my case, the application is an IDE, and it is a reasonable assumption
that the source code exists locally (and that the extension module was built
from the source in it's current location). Anyway, since I control the
source code, I'll just add a bit of code to do the trick. I was just hoping
something like this happened to be standard already that I didn't know
Perhaps something like this in the init function:
PyObject *module, *dict, *sourcefile;
module = Py_InitModule("engine", engine_methods);
dict = PyModule_GetDict(module);
sourcefile = PyStringFromString(__FILE__);
PyDict_SetItemString(dict, "__sourcefile__", sourcefile);
More information about the Python-list