【问题标题】:Logging error in Python 3.x : TypeError: a bytes-like object is required, not 'str'Python 3.x 中的日志记录错误:TypeError: a bytes-like object is required, not 'str'
【发布时间】:2020-01-30 10:23:57
【问题描述】:

我使用的是 Python 3.6.5。

使用日志记录时出现以下错误 -

"TypeError: 需要一个类似字节的对象,而不是 'str'"

它在 Python 2.x 中运行良好,我也尝试将字符串转换为 Byte 对象,但无法解决问题

if __name__ == '__main__':
    config_file = '/source/account_content_recommendation/config/sales_central_config.json'
    try:
        ### Read all the parameters -
        params = json.loads(hdfs.read_file(config_file))

        ### Create the logging csv file -
        hdfs_log_path = params["hdfs_log_path"]
        hdfs.create_file(hdfs_log_path, "starting ... ", overwrite = True)
        log_name = 'Account_Content_Matching'


        global stream
        log = logging.getLogger('Acct_Cont_Log')
        stream = BytesIO()
        handler = logging.StreamHandler(stream)
        log.setLevel(logging.DEBUG)

        for handle in log.handlers:
            log.removeHandler(handle)

        log.addHandler(handler)

        #env = sys.argv[1]
        env = 'dev'
        formatter = logging.Formatter('{0}| %(asctime)s| {1}| %(module)s| %(funcName)s| %(lineno)d| %(levelname)s| %(message)r'.format(log_name, env))
        handler.setFormatter(formatter)

        log.info("starting execution of Account_Content_Matching load")
        #log.info("sys args %s"%(str(sys.argv)))

        def flush_log():
            global stream
            msg = stream.getvalue()
            hdfs.append_file(hdfs_log_path, msg)
            stream.seek(0)
            stream.truncate(0)
            print(msg)
            sys.stdout.flush

    except Exception as error:
        raise error

我收到以下错误 -

Traceback(最近一次调用最后一次): 文件“/home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/logging/init.py”,第 994 行,在发出 流。写(味精) TypeError:需要一个类似字节的对象,而不是'str'

还有……

消息:'开始执行 Account_Content_Matching 加载' 论据:() I1001 06:29:35.870266 140241833649984:29] 开始执行 Account_Content_Matching 加载

【问题讨论】:

  • 要么使用 TextIO,要么使用 b 为您记录的所有字符串添加前缀(例如 b"bytes-string"),或者使用编码:"string".encode()
  • 感谢克里斯蒂,正如您所说,我将其转换为 StringIO 并解决了问题。这就是我所做的 - from io import StringIO ;流 = StringIO()
  • 好的!到时候我会发布答案。

标签: python python-3.x logging byte


【解决方案1】:

在您的记录器设置中,您是:

  • 使用 BytesIO 作为流
  • 向它传递字符串

这不起作用,2 必须同步。有 2 种方法可以修复它。 任一

  • 使用[Python 3.Docs]: class io.StringIO(initial_value='', newline='\n')(而不是BytesIO):

    stream = StringIO()
    
  • 在将所有字符串传递给记录器方法之前将它们转换为 字节(更复杂,并且比前者更没有意义):

    log.info("starting execution of Account_Content_Matching load".encode())  # log.info(b"starting execution of Account_Content_Matching load")  # For literals
    log.debug(some_string_var.encode())
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 2017-05-08
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多