need help: need help emmulating "import" from C

Ram Bhamidipaty ramb at sonic.net
Fri Aug 23 15:41:59 CEST 2002


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



More information about the Python-list mailing list