sys.stdin.encoding
Leo Kislov
Leo.Kislov at gmail.com
Mon Dec 11 05:04:28 EST 2006
aine_canby at yahoo.com wrote:
> Duncan Booth skrev:
>
> > aine_canby at yahoo.com wrote:
> >
> > > The following line in my code is failing because sys.stdin.encoding is
> > > Null.
> >
> > I'll guess you mean None rather than Null.
> >
> > > This has only started happening since I started working with
> > > Pydef in Eclipse SDK. Any ideas?
> > >
> > > uni=unicode(word,sys.stdin.encoding)
> > >
> > You could give it a fallback value:
> >
> > uni = unicode(word, sys.stdin.encoding or sys.getdefaultencoding())
> >
> > or even just:
> >
> > uni = unicode(word, sys.stdin.encoding or 'ascii')
> >
> > which should be the same in all reasonable universes (although I did get
> > bitten recently when someone had changed the default encoding in a system).
>
>
> Thanks for your help. The problem now is that I cant enter the Swedish
> characters åöä etc without getting the following error -
>
> Enter word> Påe
> Traceback (most recent call last):
> File "C:\Documents and Settings\workspace\simple\src\main.py", line
> 25, in <module>
> archive.Test()
> File "C:\Documents and Settings\workspace\simple\src\verb.py", line
> 192, in Test
> uni=unicode(word,sys.stdin.encoding or sys.getdefaultencoding())
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 1:
> ordinal not in range(128)
>
> The call to sys.getdefaultencoding() returns ascii. Since I can enter
> the characters åöä on the command line in Pydef/Eclipse doesn't that
> mean that the stdin is not ascii? What should I do?
The workaround in your case is:
in the beginning of your program:
import sys
if hasattr(sys.stdin, 'encoding'):
console_encoding = sys.stdin.encoding
else:
import locale
locale_name, console_encoding = locale.getdefaultlocale()
and later:
uni = unicode(word, console_encoding)
But don't think it's portable, if you use other IDE or OS, it may not
work. It would be better if PyDev implemented sys.stdin.encoding
-- Leo
More information about the Python-list
mailing list