2012-01-26 6 views
1

sys.exit()が呼び出されたときにPythonスクリプトを正しくファイナライズする最良の方法は何ですか?呼び出しsys.exit(-1) - - それはアプリ をクローズする時間だ決める - 一部のUSBガジェット を開く - ファイル をログ開いた - (あるいは、それは過酷なスロー:たとえばIronPython - sys.exit()での適切なリソース割り当て解除

私はアプリを持っています私は少しのおしゃぶりだったので、コードのいくつかの部分が実際にすべての例外をキャッチするので、私の終了例外は止まるでしょう...)

私は確かに呼ばれるいくつかのfinalize()関数が必要です通訳を終了する前にFinalize()は、USBガジェットを解放し、この順番でログファイルを閉じます。

は、私はデフ・デル・ をしようとしたが、それはないsys.exitに呼び出され、さらに私は_ デル _sが呼ばれることになるために決定することはできません。

私には救いがありますか?または、私はする必要があります: 1.最も多くのtry-catch-finally 2.いくつかの特定の例外で終了します。 3.例外キャッチのどこでも、私が捕まえているものを正確に指定していますか?

+1

'atexit'を見ましたか? http://docs.python.org/library/atexit –

答えて

1

pythonのwith文を参照してください。

class UsbWrapper(object): 
    def __enter__(self): 
     #do something like accessing usb_gadget (& acquire lock on it) 
     #usb_gadget_handle = open_usb_gadget("/dev/sdc") 
     #return usb_gadget_handle 

    def __exit__(self, type, value, traceback): 
     #exception handling goes here 
     #free the USB(lock) here 

with UsbWrapper() as usb_device_handle: 
     usb_device_handle.write(data_to_write) 

希望、USBロックが常に解放されるように、コードが例外や実行をスローするかどうかは関係ありません。

0

[OK]を私は最高の私をスイートの答えが見つかりました:推奨ソリューションのatexit用として

import sys 
try: 
    print "any code: allocate files, usb gadets etc " 
    try: 
    sys.exit(-1) # some severe error occure 
    except Exception as e: 
    print "sys.exit is not catched:"+str(e) 
    finally: 
    print "but all sub finallies are done" 
    print "shall not be executed when sys.exit called before" 
finally: 
    print "Here we can properly free all resources in our preferable order" 
    print "(ie close log file at the end after closing all gadgets)" 

を - それは素晴らしく、すべてのだろうが、それは私のpython 2.6では動作しません。それは間違いなく、ほとんどの空想だ - - ラッパー液として

import sys 
import atexit 

def myFinal(): 
    print "it doesn't print anything in my python 2.6 :(" 

atexit.register(myFinal) 

print "any code" 
sys.exit(-1) # is it pluged in? 
print "any code - shall not be execute" 

正直なところ、私はそれが良いでしょうか言うことができない...

import sys 
class mainCleanupWrapper(object): 
    def __enter__(self): 
     print "preallocate resources optionally" 

    def __exit__(self, type, value, traceback): 
     print "I release all resources in my order" 

with mainCleanupWrapper() as whatsThisNameFor: 
     print "ok my unchaged code with any resources locking" 
     sys.exit(-1) 
     print "this code shall not be executed" 

を、私は私の解決策を見つけた - しかし、率直に言ってPythonはいるようだ:私はこれを試してみましたかなり嵩張って肥大化しているかもしれません...

関連する問題