简体   繁体   中英

Python error : UnicodeEncodeError: 'ascii' codec can't encode character

I have a python script in which a function prints some lines from error file.

Getting below error when I execute the script through jenkins.

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)

Default encoding for python is UTF-8

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

I tried to export the variable PYTHONIOENCODING=UTF-8 before executing the script.

Added below line at the start of script-

# 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

you can try to use:

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

More info : UnicodeEncodeError

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