1
votes

I have a little Python code in Q_GIS which opens objects. The problem I have is that in the directory there is a character (underscore like character) that can not be encoded. The error is:

Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 10: ordinal not in range(128)

My little code is:

from os import startfile; 
proj = QgsProject.instance(); 
UriFile = str(proj.fileName()); 
img = '[% "pad" %]'; 
Path = str(os.path.dirname(UriFile)); 
startfile(Path+img)

Because of my little programming skills, I ask you to help me add some code in this little code to overcome the problem.

3

3 Answers

8
votes

I assume:

  • you are using a Python2 version
  • QgsProject.instance().fileName() is a unicode string containing a EN-DASH (Unicode char U+2013: –) this looks like a normal dash (Unicode char U+2D: -) but does not exists in ASCII nor in any common 8bits character set.

The error is then normal: in Python2 the conversion of an unicode string to a plain 8bits string uses the ASCII character set.

Workaround:
You can use an explicit encoding asking to use a replace character for unmapped ones:

UriFile = proj.fileName().encode('ascii', 'replace')

at least you will see where the offending characters occurs.

Solution:

You should either use full unicode processing (and use Python3) or make sure that all string processed are representable in you current character set (often latin1)

Alternatively, if it make sense in your use case, you could try to use the UTF8 encoding which can successfully represent any UNICODE character in 1, 2 or 3 bytes:

UriFile = proj.fileName().encode('utf8')
1
votes

Thanks for the answers,

I have found the answer in replacing str with unicode in the python code, see the code below.

from os import startfile; 
proj = QgsProject.instance();
UriFile = unicode(proj.fileName()); 
img = '[% "pad" %]'; 
Path = unicode(os.path.dirname(UriFile)); 
startfile(Path+img)

from os import startfile; 
proj = QgsProject.instance();
UriFile = unicode(proj.fileName()); 
img = '[% "pad" %]'; 
Path = unicode(os.path.dirname(UriFile)); 
startfile(Path+img)
1
votes

after a lot of search I can not find a way but by this I can ignore it

OBJECT.encode('ascii', 'ignore')