如何解决“ TypeError:需要类似字节的对象,而不是'str'”错误?

时间:2019-05-22 16:49:06

标签: python-3.x python-2.7 logging

我正在将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 个答案:

答案 0 :(得分:0)

设置日志记录基本配置时,我进行了更改 python filemode='wb'python filemode='w'并正常运行。