The output of "exec dir" vs. just "dir"

Alex Farber farber at cpan.org
Wed Mar 15 12:40:05 EST 2000


Fredrik Lundh wrote:
> Alex Farber <farber at cpan.org> wrote:
> > I am simulating Python's prompt by calling Py_CompileString() +
> > PyEval_EvalCode(), which is probably the same, what "exec" does.
> 
> try compiling with symbol set to Py_single_input...

Thank you - that helped!

> or rather, don't try that.  why not just call the "code" module
> from your C program, instead of trying to reimplement it in C?

The code below is interesting, too, thanks. 
Mike Fletcher also suggested using PyObject_Repr()...

> assuming you're program can be reached from python as an
> extension called "myprogram", here's what you need to do:
> 
> 1. write a function that takes standard output (and perhaps
> standard error) and sends it to whatever output device you
> use (a widget, over a socket, ...).   in your python initialization
> script, do:
> 
>     class myRedirect:
>         def __init__(self, type):
>             self.type = type
>         def write(self, str):
>             myprogram.write(str, self.type)
> 
>     sys.stdout = myRedirect(1)
>     sys.stderr = myRedirect(2)
> 
> where myprogram.write is something like:
> 
>     char* p;
>     int n, mode;
> 
>     if (!PyArg_ParseTuple("s#i", &p, &n, &mode))
>         return NULL;
> 
>     /* send n bytes at p to the output device */
> 
> 2. write a function that takes an interpreter object and tucks
> it away somewhere.  then create a
> 
>     interpreter = code.InteractiveConsole()
>     myprogram.setinterpreter(interpreter)
> 
> where myprogram.setinterpreter is simply:
> 
>     PyObject* global_interpreter;
> 
>     PyObject* interpreter;
> 
>     if (!PyArg_ParseTuple("O", &interpreter))
>         return NULL;
> 
>     /* hang on to this one */
>     Py_INCREF(interpreter);
>     global_interpreter = interpreter;
> 
> 3. inside your application, read lines from the user, and
> use "push" on the interpreter object to pass them on to
> the interpreter.
> 
>     PyObject* result;
> 
>     result = PyObject_CallMethod(global_interpreter, "s", line);
>     if (PyInt_AsLong(result))
>         send("... "); /* continuation prompt */
>     else
>         send(">>> "); /* standard prompt */
>     Py_DECREF(result);

Best regards
Alex



More information about the Python-list mailing list