見出し画像

Pythonで書いたプログラムが異常終了したことを報告する

Windowsでプログラムを作り、Pythonで作ったプログラムを呼び出して使います。
Pythonで異常終了した場合、Windowsのプログラムに異常終了を伝えなければなりません。

この異常終了を知らせる方法、異常終了があります。
sys.exit(1)

Windowsで言えば、環境変数のERRORLEVELですね。
プログラムが終了した時の値、WindowsのプログラムでPythonを呼び出すと取得できるはずです。

はずですと言うのは、実際に試せないからです。
Pythonのソースコードを実行プログラムに変換することが成功していないからです。

一応、サンプルソースコードを掲載します。


#ロギングを行う
import logging

#異常終了する
import sys


def TestFunction(Option1st ,Option2nd):
#関数のオプションを記録する
logging.debug('%s %i','Option1st=',Option1st)
logging.debug('%s %i','Option2nd=',Option2nd)

try:
#関数の処理をここに記載します
#計算します
CalculationResult=Option1st/Option2nd

except Exception as err:
#例外が発生したのでログファイルに記録して 、異常終了します。
logging.critical('%s %s','Exception handling occurs=',err)
return 0,False

#計算結果を記録します
logging.debug('%s %i','CalculationResult=',CalculationResult)

#計算結果を返し 、正常終了
return CalculationResult,True

def main():
#ロギングの設定
LogFormat = "%(asctime)s:%(pathname)s:%(funcName)s:%(lineno)s:%(message)s"
logging.basicConfig(filename='Python_log.log', level=logging.DEBUG,format=LogFormat)

#サンプル用の関数を呼び出し 、結果を取得
FunctionResult,Exception=TestFunction(12,0)

#関数が正常に実行できたか確認する
if Exception==False :
#例外エラーが発生している時の処理
print('No processing because an abnormality has occurred')
sys.exit(1)
return
else:
#関数の結果を表示する
print(FunctionResult)

return


#最後にmainを呼び出す
main()


#学習 #勉強 #Python #プログラミング


この記事が気に入ったらサポートをしてみませんか?