4

The program below triggers a UnicodeEncodeError on my Windows 10 machine (running Python 3.5.2) but no error at all on my Linux machine (running Python 3.3.2).

#!/usr/bin/python
import logging
str ="Antonín Dvořák"
logging.basicConfig(filename='log.txt', level=logging.INFO)
logging.info(str)

On Linux, the log file correctly contains:

INFO:root:Antonín Dvořák

On Windows, I get the following error:

enter image description here

Any ideas on what the possible cause could be for this discrepancy?

3

2 Answers 2

4

Theh default encoding of Windows (cp1252 in your case) is different from Linux (usually utf8), so you have to specify the encoding you want.

Below didn't work in Python 3.3 (still used cp1252) but did with 3.5 so it looks like a bug in 3.3. I used utf-8-sig because many Windows text editors default to an ANSI encoding (such as cp1252) without a UTF-8 BOM signature.

import logging
str ="Antonín Dvořák"
with open('log.txt','w',encoding='utf-8-sig') as s:
    logging.basicConfig(stream=s, level=logging.INFO)
    logging.info(str)
Sign up to request clarification or add additional context in comments.

Comments

3

Instead of a file name, you could pass a stream whose encoding is specified:

logging.basicConfig(
    stream=open('log.txt', 'w', encoding='utf-8'),
    level=logging.INFO
)

As for the cause, it's probably trying to open the target file using your current locale's encoding (CP1252, judging by the stack trace).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.