Non-ascii characters in an MSDOS window

Bengt Richter bokr at oz.net
Thu Oct 17 22:28:06 EDT 2002


On Thu, 17 Oct 2002 20:28:23 GMT, "Bartolomé Sintes Marco" <BartolomeSintes at ono.com> wrote:

>Hi,
>
>I am using Python 2.2.2 for Windows in a computer with a Spanish Windows 98
>SE operating
>system. I have written the following program (sample.py)
>
>print "Spanish accents: á é í ó ú"
>end = raw_input()
>
>If I run this program in IDLE (Ctrl+F5), Python writes the accents
>correctly, but if I double-click
>the sample.py file, an MS-DOS window opens and wrong symbols are written.
>
>I have tried to use sys.setdefaultencoding() in sitecustomize.py file, but I
>always get the same
>wrong characters in the MSDOS Windows no matter which encoding I use.
>
>Is there an easy way to make Python write the same characters in a MSDOS
>window than in IDLE?
>
You could try something like this version of your sample.py:
(it assumes your strings are Latin-1 encoded)
--
# sample.py
sa =  "Spanish accents: á é í ó ú"  # som we can see sample.sa interactively
class L1to437:
    import sys
    def __init__(self):
        self.so = L1to437.sys.stdout
    def on(self):
        L1to437.sys.stdout = self
    def off(self):
        L1to437.sys.stdout = self.so
    def write(self, s):
        self.so.write(s.decode('latin-1').encode('cp437'))
so437 = L1to437()

if __name__ == '__main__':
    print "Before: Spanish accents: á é í ó ú"
    so437.on()
    print "    On: Spanish accents: á é í ó ú"
    so437.off()
    print "   Off: Spanish accents: á é í ó ú"
    end = raw_input()
--

Running it:
[19:20] C:\pywk\junk>sample.py
Before: Spanish accents: ß T f = ·
    On: Spanish accents: á é í ó ú
   Off: Spanish accents: ß T f = ·

Or you can import it, and use sample.so437.on() to turn on coding of output for the DOS window:

 >>> import sample
 >>> print sample.sa
 Spanish accents: ß T f = ·
 >>> sample.so437.on()
 >>> print sample.sa
 Spanish accents: á é í ó ú
 >>> sample.so437.off()
 >>> print sample.sa
 Spanish accents: ß T f = ·

But Martin is the expert on that stuff. There may be a clean way to do it.

Regards,
Bengt Richter



More information about the Python-list mailing list