[Tutor] logging to cmd.exe
Mark Lawrence
breamoreboy at yahoo.co.uk
Mon Sep 25 12:19:04 EDT 2017
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?
C:\Users\Mark\Documents\MyPython>chcp
Active code page: 65001
C:\Users\Mark\Documents\MyPython>type mytest.py
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)
C:\Users\Mark\Documents\MyPython>mytest.py
euro sign: '€'
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
---
This email has been checked for viruses by AVG.
http://www.avg.com
More information about the Tutor
mailing list