[SOLVED] need help: need help emmulating "import" from C

Ram Bhamidipaty ramb at sonic.net
Sat Aug 24 00:18:10 EDT 2002


Ram Bhamidipaty <ramb at sonic.net> writes:

> I have embedded the Python interpreter into my application. I
> have also created a custom module that contains the core
> functionality of my application.
> 
> I want my custom module to be imported prior to running
> any user scripts - this way the user script does not
> need an explicit "import" statment.
> 
> I'm pretty sure I could use PyRun_SimpleString("import foo"), but I
> really want to know how to do this by using the lower level
> C API functions. 
> 
> In fact I traced the execution of an "import foo" statement in my
> script - just to see what the interpreter was doing. I got lost when I
> saw that the local and global dictionaries that eventually get passed
> to import_module_ex() came from the local and global frame object from
> the import statement. I need Help !! :-)
> 
> Basically I want to understand more about local and gloabl namespaces
> and how they relate to __main__.
> 
> 
> I've tried a variety of combinations of calling
> PyImport_ImportModule() and PyImport_ImportModuleEx(). But I've
> not been able to get the effect that I want. This is my current
> try (error checking removed):
> 
> main () {
>   Py_SetProgramName (argv[0]);
>   PyImport_AppendInittab ("foo", foo_func);
>   Py_Initialize ();
> 
>   m = PyImport_AddModule ("__main__");
>   d = PyModule_GetDict (m);
>   
>   PyImport_ImportModuleEx ("foo", d, d, NULL);
> 
>   PySys_SetArgv (argc-1, argv+1);
> 
>   fp = fopen (argv[1], "r");
>   stat = PyRun_SimpleFile (fp, argv[1]);
> }
> 
> The problem with this is that when the script executes (via
> PyRun_SimpleFile at the end) is that my custom module is not available
> to the script - I get NameError's. Of course if I put an explicit
> import then all is well.
> 
> Any help much appreciated.
> -Ram


Turns out the solution is to read the section in the Python reference manual
describing the import statement.

The code below successfully initializes a module. The missing part
is that an entry in the local/global dictionary needs to be added.

The new code looks like this (error checking removed):

void
func (void)
{
  FILE *fp;
  PyObject *m, *d, *m2;

  Py_SetProgramName (argv[0]);
  PyImport_AppendInittab ("foo", foo_init);
  Py_Initialize ();

  m = PyImport_AddModule ("__main__");
  d = PyModule_GetDict (m);

  m2 = PyImport_ImportModuleEx ("foo", d, d, NULL);

  PyDict_SetItemString (d, "foo", m2);

  PySys_SetArgv (argc-1, argv+1);

  fp = fopen (argv[1], "r");
  stat = PyRun_SimpleFile (fp, argv[1]);
}






More information about the Python-list mailing list