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'))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章