2017-09-28 6 views
0

書き直して、もっと明確にするが、Clark Jはそれを得たと信じている。私は次のような内容のファイルを持っています:Pythonでクリーンアップメソッドを実装する理想的な方法

class tests: 

    def test1(self): 
     create something1 

    def test2(self): 
     create something2 
    . 
    . 
    . 
    . 

    def test19(self): 
     cleanup something1 

    def test20(self): 
     cleanup something2 

test1またはtest2が失敗すると、something1、something2が残っています。 "try:finally:"を使用しているのが分かりにくいので、プログラムが終了する前にtest19とtest20が毎回実行されるように、あるいはそれを別の方法で行うのがより理想的です。基本的に私の目標は、test19とtest20がプログラムの前に常に実行されていることを確認して、他のテストで失敗を起こさないようにすることです。ありがとう。

class tests: 

    try: 

     def test1(self): 
      create something1 

     def test2(self): 
      create something2 
     . 
     . 
     . 
     . 

    finally: 

     def test19(self): 
      cleanup something1 

     def test20(self): 
      cleanup something2 

答えて

1

try finallyブロックを使用できなかった理由はありません。

また、atexitモジュールを使用することもできます。あなたのプログラムが終了した後で登録された関数を実行します。これは、Python 2とPython 3の標準ライブラリの一部です。

import atexit 

@atexit.register #decorator call only works for functions without args 
def function_to_run_on_exit(): 
    print ("doing some awesome teardown and cleanup") 

def exit_function_with_args(foo, bar): 
    print("cleaning up {} and {}").format(foo, bar)) 



atexit.register(exit_function_with_args, 'my foo', 'my bar') 
関連する問題