【发布时间】: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