[Libguestfs] [PATCH nbdkit] python: Turn python exceptions into nbdkit errors properly.

Richard W.M. Jones rjones at redhat.com
Thu Apr 5 13:32:57 UTC 2018


On Thu, Apr 05, 2018 at 08:17:00AM -0500, Eric Blake wrote:
> On 04/05/2018 07:47 AM, Richard W.M. Jones wrote:
> > ---
> >  configure.ac                   |  8 +++++++
> >  plugins/python/python.c        | 51 +++++++++++++++++++++++++++++++++++++++---
> >  tests/Makefile.am              |  1 +
> >  tests/python-exception.py      | 45 +++++++++++++++++++++++++++++++++++++
> >  tests/test-python-exception.sh | 42 ++++++++++++++++++++++++++++++++++
> >  5 files changed, 144 insertions(+), 3 deletions(-)
> > 
> 
> > +/* Convert bytes/str/unicode into a string.  Caller must free. */
> > +static char *
> > +python_to_string (PyObject *str)
> > +{
> > +  char *r;
> > +
> > +  if (str) {
> > +#ifdef HAVE_PYUNICODE_ASUTF8
> > +    if (PyUnicode_Check (str)) {
> > +      r = PyUnicode_AsUTF8 (str);
> > +      r = strdup (r);
> > +      return r;
> 
> Any simpler to just write:
> return strdup (PyUnicode_AsUTF8 (str));
> 
> instead of using the temporary variable r?

Yes I can change that.  The consequence of multiple refactorings
while I was trying to work out how to convert PyObject to char *
(you'd think that would be easy ...)

> >  static int
> >  check_python_failure (const char *callback)
> >  {
> >    if (PyErr_Occurred ()) {
> > -    nbdkit_error ("%s: callback failed: %s", script, callback);
> > -    /* How to turn this into a string? XXX */
> > -    PyErr_Print ();
> > +    PyObject *type, *error, *traceback, *error_str;
> > +    char *error_cstr;
> > +
> > +    /* Convert the Python exception to a string.
> > +     * https://stackoverflow.com/a/1418703
> > +     * But forget about the traceback, it's very hard to print.
> > +     * https://stackoverflow.com/q/1796510
> > +     */
> > +    PyErr_Fetch (&type, &error, &traceback);
> > +    PyErr_NormalizeException (&type, &error, &traceback);
> > +    error_str = PyObject_Str (error);
> > +    error_cstr = python_to_string (error_str);
> > +    nbdkit_error ("%s: %s: error: %s",
> > +                  script, callback, error_cstr ? : "<unknown>");
> 
> Okay, not the first use of that gcc extension.

I guess I'll change this one too, it's not a case where we
actually want to avoid a side effect.

Thanks,

Rich.

-- 
Richard Jones, Virtualization Group, Red Hat http://people.redhat.com/~rjones
Read my programming and virtualization blog: http://rwmj.wordpress.com
Fedora Windows cross-compiler. Compile Windows programs, test, and
build Windows installers. Over 100 libraries supported.
http://fedoraproject.org/wiki/MinGW




More information about the Libguestfs mailing list