无法弄清楚如何从 utf-16 文件中读取并将其系统记录到 utf-8

cant figure out how to read from utf-16 file and syslog it out to utf-8

我正在尝试获取 UTF-16 格式的文件,然后 syslog 将它以 UTF-8 格式发送到 syslog 服务器。我对 python 和编程还很陌生。 一切正常,只是它没有在 syslog 中以 UTF-8 格式发送出去。

代码

import logging
import logging.handlers
import tailer
import os
import codecs

logger = logging.getLogger('myLogger')
logger.setLevel(logging.INFO)

#add handler to the logger
handler = logging.handlers.SysLogHandler(address=('x.x.x.x', 514))

#add formatter to the handler
formatter = logging.Formatter('')

handler.formatter = formatter
logger.addHandler(handler)

while True:
    for line in tailer.follow(open('z:\ERRORLOG')):
        logger.info(str.decode('utf-8'), line)

i also tried the below at the end

while True:
for line in tailer.follow(open('z:\ERRORLOG')):
    logger.info(str(line, 'utf-8'))

打开文件时只需使用附加参数encoding。 简单示例:

with open('utf-16.txt', 'r', encoding='utf-16') as fr:
    with open('utf-8.txt', 'w', encoding='utf-8') as fw:
        for line in fr:
            fw.write(line)

你的情况:

while True:
    with open('z:\ERRORLOG', encoding='utf-16') as fr:
        for line in tailer.follow(fr):
            logger.info(line)