简体   繁体   中英

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:

在此输入图像描述

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

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)

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM