python dbus: dealing with strings

Neal H. Walfield neal at walfield.org
Wed Sep 14 08:11:31 PDT 2011


Hi Simon,

Thanks for the helpful reply.

This is the code that I eventually settled on.  Instead of casting the
object to a dbus.UTF8String or dbus.String, I do my best to coerce the
object to a unicode object; I decided requiring that the caller pass a
unicode object was too much of a burden.

  def _str_to_dbus_str(s, strict=False):
      """
      Given a string, do our best to turn it into a unicode compatible
      object.
      """
      if issubclass(s.__class__, unicode):
          # It's already unicode, no problem.
          return s
   
      # It's not unicode.  Convert it to a unicode string.
      try:
          return unicode(s)
      except UnicodeEncodeError:
          logger.exception("Failed to convert '%s' to unicode" % s)
          if strict:
              raise
          else:
              return unicode(s, errors='replace')

Thanks,
Neal


More information about the dbus mailing list