From: Tutor <tutor-bounces+sjeik_appie=hotmail....@python.org> on behalf of 
Mark Lawrence via Tutor <tutor@python.org>
Sent: Monday, September 25, 2017 4:19 PM
To: tutor@python.org
Subject: Re: [Tutor] logging to cmd.exe
    
On 25/09/2017 14:20, Albert-Jan Roskam wrote:
> Hi,
> 
> 
> With Python 3.5 under Windows I am using the logging module to log messages 
> to stdout (and to a file), but this occasionally causes logging errors 
> because some characters cannot be represented in the codepage used by cmd.exe 
> (cp850, aka OEM codepage, I think).  What is the best way to prevent this 
> from happening? The program runs fine, but the error is distracting. I know I 
> can use s.encode(sys.stdout.encoding, 'replace') and log that, but this is 
> ugly and tedious to do when there are many log messages. I also don't  
> understand why %r (instead of %s) still causes an error. I thought that the 
> character representation uses only ascii characters?!
> 
> 
> import logging
> import sys
> 
> assert sys.version_info.major > 2
> logging.basicConfig(filename="d:/log.txt", 
> level=logging.DEBUG,format='%(asctime)s %(message)s')
> handler = logging.StreamHandler(stream=sys.stdout)
> logger = logging.getLogger(__name__)
> logger.addHandler(handler)
> 
> s = '\u20ac'
> logger.info("euro sign: %r", s)
> 
> 
> 
> --- Logging error ---
> Traceback (most recent call last):
>    File "c:\python3.5\lib\logging\__init__.py", line 982, in emit
>      stream.write(msg)
>    File "c:\python3.5\lib\encodings\cp850.py", line 19, in encode
>      return codecs.charmap_encode(input,self.errors,encoding_map)[0]
> UnicodeEncodeError: 'charmap' codec can't encode character '\u20ac' in 
> position 12: character maps to <undefined>
> Call stack:
>    File "q:\temp\logcheck.py", line 10, in <module>
>      logger.info("euro sign: %r", s)
> Message: 'euro sign: %r'
> Arguments: ('\u20ac',)
> 
> 
> Thanks in advance for your replies!
> 
> 
> Albert-Jan
> 

Rather than change your code can you change the codepage with the chcp 
command?


========> Good to keep in mind, but my objection would be similar to that with 
specifying the PYTHONIOENCODING variable: one needs to change the environment 
first before the script runs without errors.


C:\Users\Mark\Documents\MyPython>chcp
Active code page: 65001


========> Wow! cmd.exe can use cp65001 aka utf8??? I always thought 65001 was 
not a 'real' codepage, even though some locales (e.g. Georgia) use it [1]. Why 
does cmd.exe still use cp850?

[1] https://docs.moodle.org/dev/Table_of_locales

PS: sorry about the missing quote (>>) markers. Hotmail can't do this. Is Gmail 
better?
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to