Reputation: 343
I have a python program and I am using pyqt
. I use QFileDialog
to select directory and then run a script with that directory. The problem is that if the directory name is in Greek the program stops with exception
ascii codec can't encode characters in position
If the name of the directory is in English everything works fine. How can i solve that?
try:
directory = QtGui.QFileDialog.getExistingDirectory(MainWindow,"Please select directory ") #Select the directory for check
if directory != "":
directory = str(directory)
self.updatedirectory(directory)
except Exception as e:
self.AlertMessage(e)
Upvotes: 0
Views: 2092
Reputation: 120798
Do not use str()
to convert a QString
: always use unicode()
:
directory = unicode(directory)
In Python 2, str()
converts to bytes. If you use it on a string object containing unicode, it will try to encode it using the default codec, which is "ascii". So, if the string contains non-ascii characters, you will obviously get an error:
>>> from PyQt4 import QtCore
>>> s = QtCore.QString(u'Γειά σου Κόσμε!')
>>> x = str(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3:
ordinal not in range(128)
but if you use unicode()
, it will convert the QString
to a python unicode object directly (i.e. without needing to do any encoding/decoding):
>>> x = unicode(s)
>>> type(x)
<type 'unicode'>
>>> print x
Γειά σου Κόσμε!
Upvotes: 2
Reputation: 11869
Consider telling PyQt to use native Python unicode strings
Before you import PyQt, insert:
import sip
sip.setapi('QString', 2)
QtCore.QString
will no longer exist (you will get exceptions if you try and manually create a QString
) and all PyQt methods that previously returned a QString
will return a Python unicode string.
Note: Don't try to typecast the unicode string with str()
. Just use the result of getExistingDirectory
directly.
Upvotes: 3
Reputation: 10961
QtGui.QFileDialog
returns a QString
, if you want to extract the string
out of it, use one of its methods, for instance QString.toLatin1
.
EXAMPLE:
>>> from PyQt4.QtCore import QString
>>>
>>> s = QString(u'Γεια σου')
>>>
>>> s
PyQt4.QtCore.QString(u'\xce\x93\xce\xb5\xce\xb9\xce\xb1 \xcf\x83\xce\xbf\xcf\x85')
>>> print s
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print s
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-7: ordinal not in range(128)
>>>
>>>print str(s.toLatin())
Γεια σου
There are other methods that you might want to try to get your desired output.
So, in your case, this might work for you:
directory = str(directory.toLatin())
Upvotes: 1