1

sys.exit() が呼び出されたときに Python スクリプトを適切にファイナライズする最良の方法は何ですか?

たとえば、私は次のようなアプリを持っています: - ログファイルを開いた - USB ガジェットを開いた - アプリを閉じる時が来たと判断した - sys.exit(-1) を呼び出す - (または、厳しい例外をスローする - しかし、私は最初の方法を好む少し豚だったし、コードの一部の部分は実際にすべての例外をキャッチし、終了例外を停止します...)

次に、インタープリターを終了する前に確実に呼び出される finalize() 関数が必要になります。Finalize() は、まさにこの順序で USB ガジェットを解放し、ログ ファイルを閉じます。

def delを試しましたが、sys.exit で呼び出されず、さらに _ del _s が呼び出される順序を決定できません。

私に何か救いはありますか?または、私がしなければならないことはありますか?

4

2 に答える 2

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 ロックは常に解放されます。

于 2012-01-26T18:13:17.220 に答える
0

わかりました、私に最も適した答えを見つけました:

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)"

推奨される解決策については atexit - それは素晴らしいことですが、私の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"

Wrapper ソリューションに関しては - それは間違いなく最もファンシーです - しかし、正直なところ、それがどのように優れているかは言えません...

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はかなりかさばって肥大化しているようです...

于 2012-01-27T11:06:10.797 に答える