problem using import from PyRun_String

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Apr 10 02:16:42 EDT 2008


En Wed, 09 Apr 2008 13:31:22 -0300, Patrick Stinson  
<patrickkidd.lists at gmail.com> escribió:

> Well, I eventually want to add an import hook, but for now I'd rather  
> just
> get the import statement working normally again.
> I have embedded python as a scripting engine in my application. To do  
> this,
> I create a new empty module, run the script text using PyRun_String()
> passing the module's __dict__ as locals and globals. This populates the
> module's __dict__ with the resulting object references from the script  
> text.

Instead of PyRun_String, use PyImport_ExecCodeModuleEx, which takes care  
of setting __builtins__ and other details.
You will need to compile the source first (using Py_CompileStringFlags)  
which is a good thing anyway, to help catching errors.

> As I said before I must be forgetting some other module init stuff  
> because I
> had to manually populate the modules' __dict__ with references from the
> __builtin__ module in order to get the basic stuff like abs, range, etc.

That's not exactly what CPython does; if you inspect globals() you don't  
see abs, range, etc. Instead, there is a __builtins__ attribute (note the  
"s") that points to the __builtin__ module or its __dict__.

> I understand what __builtin__ is used for, but the C struct pointing to  
> the
> code frame that contains the import statement has a builtin member that
> apparently does not contain the __import__ function, hence my question.
> There must be some difference in the way code is parsed and a copy of the
> __builtin__ module is passed normally and the way I am doing it.

When a frame builtins != internal builtins, Python runs in "restricted  
execution mode", and disallows access to some objects and attributes, I  
think that __import__ is one of them.
See http://docs.python.org/lib/module-rexec.html
(That's why it's important to use the right way to create a module)

> So, finding the place where this module bootstrapping normally happens  
> would
> be awesome, because I sort of feel like I'm hacking this method running  
> into
> problems like this.

Exactly. The simplest way would be to save the source code on disk and  
just import it, letting Python do all the dirty work. But  
compiling+PyImport_ExecCodeModule should work, I presume - any feedback is  
welcome!

-- 
Gabriel Genellina




More information about the Python-list mailing list