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

Fredrik Lundh effbot at telia.com
Wed Mar 15 02:45:14 EST 2000


Alex Farber <farber at cpan.org> wrote:
> when I enter "dir" on the Python interactive prompt,
> I get "<built-in function dir>". But entering "exec 'dir'",
> outputs nothing. To get the same result, I have to enter
> "exec 'print dir'" (w/o double quotes). The same is true for:
>
>    3              vs.           exec 3
>  globals()        vs.         exec "globals()"
>
> Why is it this way? Can I change it? I am asking, because
> 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...

> It works okay, but I'd like to get rid of the difference
> described above. Thank you.

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?

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);

should take about 30 minutes to have this up and running.

hope this helps!

</F>





More information about the Python-list mailing list