見出し画像

テキストファイルへの保存を忘れている

基本的な技術で何かを忘れていました。
何を忘れたのかと言えば、ファイルへの保存です。

これが出来なければ、呼び出されたプログラムへ計算結果などを連絡できません。
エラーレベルで計算結果を返す方法もありますが、0~255の数値しか返せないので実用性はありません。

追記モードで変数を保存する場合、こんな感じです。
with open('save.txt',mode='a') as fileP:
fileP.write('%i\n' % FunctionResult)


全体のソースコードはこんな感じです。

#ロギングを行う
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, 3)

#関数が正常に実行できたか確認する
if Exception==False :
#例外エラーが発生している時の処理
print('No processing because an abnormality has occurred')
sys.exit(1)
return
else:
#関数の結果をファイルに出力する
#追記モードで保存
with open('save.txt',mode='a') as fileP:
#整数型変数を文字列で出力し 、改行を付加して保存
fileP.write('%i\n' % FunctionResult)

return


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

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





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