天天看点

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'))