Re: How to embed Python in an application?

Guido.van.Rossum@cwi.nl
Fri, 24 Mar 1995 13:43:25 +0100

> 1) In my code I include a module with its table
> and initialization function.
>
> 2) when I start my application, I call init_all()
> and then init_foo(), where foo is my module.
>
> 3) I run_command("import foo"). Henceforth the functions
> of foo will be available to every program as foo.func1,
> foo.func2. etc., because the import was at the level
> of __main__.
>
> 4) Whenever I want to execute a script, I call run_command(),
> etc.
>
> 5) When I'm finished I call goaway();

This is basically correct. You don't even need to call your own
initfoo(), it is automatically called when you do "import foo" as long
as there's an entry for foo in the table in config.c.

This way, all your scripts will run in the same __main__ module, which
will keep hold on to any values left there by previous scripts. It's
up to you if you like that -- you could clean up after a script, or
initialize a new environment for each new run.

> Next step: all the function I consider receive a string or
> an integer, and return (possibly) a string. Thus, I just
> have to start each such function with
>
> getargs(args, "s", &p) or getargs(args, "s", &i)
^i please!

> and exit with a
>
> return mkvalue("s", r), where char *r holds the return value.
>
> Of course if there is an error I have to call err_setstr().

OK.

> Finally: I really need to be able to call my functions
> func1, func2,..., and not foo.func1, foo.func2 etc. Is
> there a way to obtain this? For otherwise all existing scripts
> will break!

Instead of "import foo", you can run_command("from foo import *").

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>