gpt4 book ai didi

python-3.x - 如何修复python中的 "TypeError: a bytes-like object is required, not ' str'"错误?

转载 作者:行者123 更新时间:2023-12-04 13:41:39 24 4
gpt4 key购买 nike

我正在将 python 2.7 代码升级到 python 3.6,但是每次我尝试使用日志记录在控制台上写一些东西时,我都会收到此错误

TypeError: a bytes-like object is required, not '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: ()

最佳答案

设置日志记录基本配置时,我更改了python filemode='wb'python filemode='w'它工作正常。

关于python-3.x - 如何修复python中的 "TypeError: a bytes-like object is required, not ' str'"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56261606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com