简体   繁体   中英

Python crashing when using logging and setting locale on Windows 10

I am using a recipe from this answer to get logging to a file and to console in UTF-8 instead of system encoding on Windows (in my case cp1250) and my python process crashes (sic:) on the last line below with:

Process finished with exit code -1073740940 (0xC0000374)

I am running Windows 10 (ver: 10.0.18362.1171) and Python 3.8.6 (x64).

import logging
import locale

log = logging.getLogger(self.dict_letters)
log.setLevel(logging.DEBUG)

console_log = logging.StreamHandler()  # create console handler and set level to debug
console_log.setLevel(LOGGING_LEVEL_CONSOLE)
console_log.setFormatter(logging.Formatter('%(levelname)s - %(message)s'))
log.addHandler(console_log)

file_log = logging.FileHandler('logfile.log'), 'w', 'utf-8')
file_log.setFormatter(logging.Formatter('%(asctime)s | %(levelname)s | %(message)s'))
file_log.setLevel(LOGGING_LEVEL_FILE)
log.addHandler(file_log)

# ensure logging works for Unicode (as per: https://stackoverflow.com/a/22320208/6573902)
if locale.getpreferredencoding().upper() != 'UTF-8':
    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

After many different experiments I realized that on Windows 10 with the recent update (one after August 2020) setting locale can be dangerous and can cause exception ( 0xc0000374 ) with Python x64 versions: 3.8.2, 3.9, 3.8.6, 3.7.1 (and potentially others) for system encoding set to cp1250 (and potentially others).

Even if previously it was benign, currently it causes python process to crash.

Removing the following lines did not cause any output issues on Windows (both console and logfile are UTF-8):

if locale.getpreferredencoding().upper() != 'UTF-8':
    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

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