Re: Make the "python" command resemble the standard Python interpreter

Khoo Yit Phang
2012-01-11T21:28:42Z

Hi,

On Jan 11, 2012, at 3:51 PM, Tom Tromey wrote:

> Yit> For "python" with arguments, this prints the results of expressions,
> Yit> e.g., "python 1 + 2" will print "3" (previously, it will not print
> Yit> anything).
>
> Did you run the test suite? I'm curious if this caused any failures.
>
> On balance, I'm ok with this idea, since I don't think we make many
> promises about CLI output remaining the same across versions.

I'm still trying to figure out how to run the testsuite and understand the output. Is it possible to just run the Python ones, to not take so long?

> Yit> It also hooks GDB's readline wrappers
> Yit> (command_line_input) to Python so that line editing and history
> Yit> editing works. Additionally, Python's standard readline module is
> Yit> stubbed out because it conflicts with GDB's use of readline.
>
> Can you expand more on how it conflicts?
>
> I think it would be better to make it not conflict somehow.

Both GDB and Python's readline module and methods attempt to configure libreadline, clobbering each others configuration. There doesn't seem to be any support in libreadline for reentrancy. It may be possible to implement a wrapper around readline for Python, but that's another patch, I think.

> Yit> + TRY_CATCH (except, RETURN_MASK_ALL)
> Yit> + {
> Yit> + struct cleanup *cleanup = gdbpy_suspend_sigint_handler ();
> Yit> + p = command_line_input (prompt, 0, "python");
> Yit> + do_cleanups (cleanup);
> Yit> + }
> Yit> +
> Yit> + /* Detect Ctrl-C and treat as KeyboardInterrupt. */
> Yit> + if (except.reason == RETURN_QUIT)
> Yit> + return NULL;
>
> Does this case need the Python exception to be set? If not, I think it
> would be good to expand this comment to explain the situation.

In this case, no, since PyOS_ReadlineFunctionPointer is supposed to return NULL upon Ctrl-C, from what I can gather. That comment is misleading, I'll change it.

> Yit> + m = PyImport_AddModule ("__main__");
> Yit> + if (m == NULL)
> Yit> + error (_("Error while executing Python code."));
>
> You have to do something with the Python exception here.
> Usually we use gdbpy_print_stack, but sometimes other things are
> appropriate.

Okay.

> Yit> + d = PyModule_GetDict (m);
>
> Do we need error checking?
> I didn't look at the API docs.

Nope, "this function never fails".

> Yit> + v = PyRun_StringFlags (command,
> Yit> + from_tty ? Py_single_input : Py_file_input,
> Yit> + d, d, NULL);
> Yit> + if (v == NULL)
> Yit> + {
> Yit> + int interrupt = PyErr_ExceptionMatches (PyExc_KeyboardInterrupt);
> Yit> + PyErr_Print ();
>
> gdbpy_print_stack.
>
> Yit> + if (! interrupt)
> Yit> + error (_("Error while executing Python code."));
>
> Why the special case for interrupts here?

This is because PyErr_Print clears the error, annoyingly enough, so I can't check whether it's a KeyboardInterrupt after PyErr_Print.

Yit
January 11, 2012