首页 > 解决方案 > Python错误:UnicodeEncodeError:'ascii'编解码器无法编码字符

问题描述

我有一个 python 脚本,其中一个函数从错误文件中打印一些行。

当我通过詹金斯执行脚本时出现以下错误。

release/bin/eat2/eat.py", line 553, in _runtest
    print('ERROR:' + msg)
UnicodeEncodeError: 'ascii' codec can't encode character '\u0447' in position 315: ordinal not in range(128)

python的默认编码是UTF-8

>>> import sys
>>> sys.getdefaultencoding()
'utf-8'

我尝试PYTHONIOENCODING=UTF-8在执行脚本之前导出变量。

在脚本开头添加以下行 -

# coding: utf8

def _check_gpderrors(gdplogfile):
    LOGERROR_REGEX = re.compile("^\d+-\d+-\d+ \d+:\d+:\d+ Error:")

    errors = []
    import codecs
    f = codecs.open(logfile, 'r', encoding='utf-8')
    for line in f:
        if re.match(LOGERROR_REGEX, line):
            errors.append(line.strip())
    f.close()
    return errors

errors = {}
errors = _check_gdperrors(log_file)
for error in errors:
        msg = project_info + ': execution failed with error: ' + error + '\n'
        print('ERROR:' + msg)
        logs.append(msg)
        script_error = True

标签: pythonencoder

解决方案


你可以尝试使用:

print('ERROR:' + msg.encode('ascii', 'ignore').decode('ascii'))

更多信息:UnicodeEncodeError


推荐阅读