sys.stderr.write: ‘NoneType‘ object has no attribute - 附python异常信息打印日志

问题背景

python脚本引用keras包读取模型执行预测,成功
使用c++构造python环境,读取python脚本并执行,成功
使用c#调用上述c++工程打包dll,使用vs编译并执行,成功
使用vs对上述c#生成exe文件,执行exe,失败报错

问题原因

通过日志打印,取得问题原因,python构建时丢失stderr通道
keras包构建时需要使用stderr输出backend信息,导致加载失败

import logging
tim = time.strftime('%y%m%d%H%M%S')
logging.basicConfig(level = logging.INFO,
                    filename = 'log-{}.txt'.format(tim),
                    filemode = 'w',
                    format = '%(asctime)s - %(levelname)s: %(message)s')
try:
	sys.stderr.write('hello')
	return 'helloworld'
except Exception:
	error = ''.join(traceback.format_exception(*sys.exc_info()))  # 将异常信息转为字符串
	logging.warning(error)
2020-04-14 20:42:05,646 - WARNING: Traceback (most recent call last):
  File "E:\pythontest\pythontest\bin\x64\Debug\app5.py", line 32, in reco_test1
    sys.stderr.write('hello')
AttributeError: 'NoneType' object has no attribute 'write'
问题解决

为sys添加keras库路径,并添加stderr通道

# py文件头部添加
import os, sys
sys.path.append(r'D:\environment\anaconda3.7\Lib\site-packages')
for _name in ('stdin', 'stdout', 'stderr'):
	if getattr(sys, _name) is None:
		setattr(sys, _name, open(os.devnull, 'r' if _name == 'stdin' else 'w'))
异常日志打印
import sys
import traceback

traceback.print_exc()
print(traceback.format_exc())
print(''.join(traceback.format_exception(*sys.exc_info())))
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值