当前位置: 首页 > 知识库问答 >
问题:

如何修复python中的“TypeError:a bytes-like-object是必需的,而不是'str'”错误?

吉泰宁
2023-03-14

我升级一个python 2.7代码到python 3.6,但每次我试图写一些控制台上使用日志记录我得到这个错误

TypeError:需要类似字节的对象,而不是“str”

我读过大多数与此类似的问题,但没有一个有效。

# mainTest.py module
from config import logger
log = logger.getLogger(__file__)

def function():
    message = "testing"
    log.info(message)
    # code
# logger.py
import logging
import os
import classpathDir as cf


def getLogger(loggerForFile):
    logger = logging.getLogger(os.path.basename(loggerForFile))
    if not logger.handlers:
        logging.basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                            datefmt='%d/%m/%Y %I:%M:%S %p', filename=cf.ROOT_DIR + "/output/processing.log",
                            filemode='wb', level=logging.DEBUG)
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        # set a format which is simpler for console use
        formatter = logging.Formatter('%(asctime)s %(name)-12s: %(levelname)-8s %(message)s',
                                      datefmt='%d/%m/%Y %I:%M:%S')
        # tell the handler to use this format
        console.setFormatter(formatter)
        # add the handler to the root logger
        logger.addHandler(console)
    return logger


if __name__ == '__main__':
    print("Logging config module")

当我在python2.7上使用相同的代码时,我得到了以下输出:

22/05/2019 01:38:11 mainTest.py   : INFO     testing

在使用相同代码的python 3.6上,我遇到了以下错误:

22/05/2019 03:17:59 mainRF.py   : INFO     testing
--- Logging error ---
Traceback (most recent call last):
  File "/usr/lib/python3.6/logging/__init__.py", line 996, in emit
    stream.write(msg)
TypeError: a bytes-like object is required, not 'str'
Call stack:
  File "mainTest.py", line 126, in <module>
    run_combinations()
  File "mainTest.py", line 20, in run_combinations
    log.info(message)
Message: 'testing'
Arguments: ()

共有1个答案

佴飞驰
2023-03-14

设置日志基本配置时,我将pythonfilemode='wb'更改为pythonfilemode='w',并且工作正常。

 类似资料: