[Tutor] Conflict with encoding in console view and file dump

Peter Otten __peter__ at web.de
Fri Jul 30 14:01:27 CEST 2010


Alex Baraibar wrote:

> Hello, would you please look at the comments in the code and help me with
> an answer?
> Thanx.
> 
> # -*- coding: cp1252 -*-
> 
> def festivos():
>     fest = [ 'Any Nou:\t\t\t1 de enero',
>              'Reis:\t\t\t\t6 de enero',
>              'Festa del Treball:\t\t1 de mayo',
>              'Sant Joan:\t\t\t24 de junio',
>              u'La Assumpció:\t\t\t15 de agosto',
>              'La Diada:\t\t\t11 de septiembre',
>              u'La Mercè:\t\t\t24 de septiembre',
>              'La Hispanitat:\t\t\t12 de octubre',
>              'Tots Sants:\t\t\t1 de novembre',
>              u'La Constitució:\t\t\t6 de desembre',
>              u'La Concepció:\t\t\t8 de desembre',
>              'Nadal:\t\t\t\t25 de desembre',
>              'Sant Esteve:\t\t\t26 de desembre' ]
>     return fest
> 
> def separador( num, char ):
>     return char * num
> 
> # --- Main ---
> dias = festivos()
> print "Los festivos fijos anuales son:\n"
> for element in dias:
>     sep = separador( 50, '-' )
> 
>     # If I turn off encoding latin-1, accented characters look
>     # wrong when I output them to a file from the command line, but
>     # if I turn on encoding, accented characters look
>     # wrong in the console view.
>     print element.encode( 'latin-1' )
> 
>     print sep
> raw_input()

Hm, I would expect an exception when you redirect the output to a file.
If you add

import sys
print >> sys.stderr, sys.stdout.encoding

what does the above print 
(a) when you print to the console
(b) when you redirect to a file?

Peter



More information about the Tutor mailing list