3

I've developed a plugin for QGIS 2.12 which uses data that is encoded in UTF-8. The plugin works fine for 2.12, but when I try to start it in QGIS 2.14 it throws me the following error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 4: ordinal not in range(128)

The code snippet which causes the exception is

value = QLabel(str(feature[field]).decode('utf-8')).

In former cases the error was thrown because I forgot to decode the characters, but I do convert them in that case. I already tried to remove the str() and the .decode('utf-8') calls, but the exception still gets thrown.

Why does this work for QGIS Lyon but not for QGIS Essen?

6
  • What's the output of print(feature[field])? Commented Mar 16, 2016 at 10:58
  • The output is E.-Mühsam-Str. I think python tries to convert it into ascii as it is the standard encoding, but I also added # -*- coding: utf-8 -*- at the top of every file. I resolved the issue just now by explicitly setting the coding to uft-8: reload(sys) sys.setdefaultencoding('utf-8') Now it works, although that might not be the most convenient solution.. Nevertheless thank you for your answer!
    – TobsenB
    Commented Mar 16, 2016 at 11:07
  • It depends on the details, but maybe it's better to fix the system than this code stackoverflow.com/a/7105835/2319028 Commented Mar 16, 2016 at 11:10
  • I guess it would be in most of the cases, but in my case the plugin has to be portable so that it can easily be installed on computers of persons who are not so much into programming. Thanks anyway for providing another approach!
    – TobsenB
    Commented Mar 16, 2016 at 11:16
  • Are you sure it's not a local issue and the workaround is also required on other peoples' computers? Commented Mar 16, 2016 at 11:18

1 Answer 1

1

Ok, I just found a workaround by explicitly prevent python from using the ascii coding as standard:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

It might not be very elegant, but the exception is not thrown anymore. But it should be noted that the QGIS embedded python console stops outputting any information after reloading the plugin using PluginReloader.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.