简体   繁体   English

Python 在 Windows 上使用日志记录和设置语言环境时崩溃 10

[英]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:我正在使用这个答案中的一个方法来记录到一个文件并在 UTF-8 中进行控制台,而不是在 Windows 中进行系统编码(在我的例子中是 cp1250),我的 python 进程在下面的最后一行崩溃(原文如此:):

Process finished with exit code -1073740940 (0xC0000374)进程结束,退出代码为 -1073740940 (0xC0000374)

I am running Windows 10 (ver: 10.0.18362.1171) and Python 3.8.6 (x64).我正在运行 Windows 10(版本:10.0.18362.1171)和 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).经过许多不同的实验后,我意识到在 Windows 10 上使用最近的更新(2020 年 8 月之后的一次)设置区域设置可能很危险,并且可能导致异常( 0xc0000374 )Python x64 版本:3.8.2、3.9、3.8.6、3.7.1 (可能还有其他)系统编码设置为 cp1250(可能还有其他)。

Even if previously it was benign, currently it causes python process to crash.即使以前它是良性的,目前它也会导致 python 进程崩溃。

Removing the following lines did not cause any output issues on Windows (both console and logfile are UTF-8):删除以下行不会导致 Windows 出现任何 output 问题(控制台和日志文件均为 UTF-8):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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