Python program does not work on Windows, but not on Linux

In the program below, a UnicodeEncodeError is fired on my computer running Windows 10 (running Python 3.5.2), but there is no error 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 could be causing this mismatch?

+4
source share
2 answers

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

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

As for the reason, he is probably trying to open the target file using the current locale encoding (CP1252, judging by the stack trace).

+3
source

Windows (cp1252 ) Linux ( utf8), .

Python 3.3 ( cp1252), 3.5, 3.3. utf-8-sig, Windows ANSI- (, cp1252) UTF-8.

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)
+4

Source: https://habr.com/ru/post/1652257/


All Articles