Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python program fails on Windows but not on Linux

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?

like image 679
Anthony Avatar asked Mar 12 '23 08:03

Anthony


1 Answers

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)
like image 95
Mark Tolonen Avatar answered Mar 21 '23 08:03

Mark Tolonen