[Python-Dev] Generalised String Coercion

Michael Hudson mwh at python.net
Mon Aug 8 11:29:50 CEST 2005


"M.-A. Lemburg" <mal at egenix.com> writes:

> Set the external encoding for stdin, stdout, stderr:
> ----------------------------------------------------
> (also an example for adding encoding support to an
> existing file object):
>
> def set_sys_std_encoding(encoding):
>     # Load encoding support
>     (encode, decode, streamreader, streamwriter) = codecs.lookup(encoding)
>     # Wrap using stream writers and readers
>     sys.stdin = streamreader(sys.stdin)
>     sys.stdout = streamwriter(sys.stdout)
>     sys.stderr = streamwriter(sys.stderr)
>     # Add .encoding attribute for introspection
>     sys.stdin.encoding = encoding
>     sys.stdout.encoding = encoding
>     sys.stderr.encoding = encoding
>
> set_sys_std_encoding('rot-13')
>
> Example session:
>>>> print 'hello'
> uryyb
>>>> raw_input()
> hello
> h'hello'
>>>> 1/0
> Genpronpx (zbfg erprag pnyy ynfg):
>   Svyr "<fgqva>", yvar 1, va ?
> MrebQvivfvbaReebe: vagrtre qvivfvba be zbqhyb ol mreb
>
> Note that the interactive session bypasses the sys.stdin
> redirection, which is why you can still enter Python
> commands in ASCII - not sure whether there's a reason
> for this, or whether it's just a missing feature.

Um, I'm not quite sure how this would be implemented.  Interactive
input comes via PyOS_Readline which deals in FILE*s... this area of
the code always confuses me :(

Cheers,
mwh

-- 
 As it seems to me, in Perl you have to be an expert to correctly make
 a nested data structure like, say, a list of hashes of instances.  In
 Python, you have to be an idiot not  to be able to do it, because you
 just write it down.             -- Peter Norvig, comp.lang.functional


More information about the Python-Dev mailing list