Hooking __import__ when embedding the interpreter

Stefan Bellon sbellon at sbellon.de
Fri Jun 29 17:05:55 EDT 2007


I think I solved all my three questions for myself now ...

On Fri, 29 Jun, Stefan Bellon wrote:

> 1) The above code seems to work ok when using the "import" statement,
>    but it does not when using the dynamic __import__ function. If
>    using it that way, I get:
> 
> >>> sys=__import__("sys")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> SystemError: new style getargs format but argument is not a tuple
> 
>    What am I missing in order to get the __import__ function covered
>    as well?

static PyMethodDef import_hook[] =
{   
    {"__import__", __import__, METH_VARARGS, import_doc},
    {NULL, NULL}
};

Adding the METH_VARARGS solved this, now the __import__ function is
intercepted as well.

> 2) Another point is, that I need to check _from where_ the module is
>    imported. In fact, this is going to become part of the consistency
>    check condition. How can I find out from which module the import
>    was initiated?
> 
> 
> 3) My final point is related to 2) ... if I get to the module object,
>    then how do I get at the source file name of that? I noticed that
>    when a .pyc is available, then this is preferred. I'd like to get
>    at the .py file itself. Is this available or do I just have to
>    strip off the trailing 'c' (or 'o'?) if present (seems hacky to
>    me).

By not focusing on the module but using
sys._getframe().f_code.co_filename I solved point 2 and 3 in one go.

I'm still looking forward to comments regarding this issue. ;-)

-- 
Stefan Bellon



More information about the Python-list mailing list