1

调用 sys.exit() 时正确完成 python 脚本的最佳方法是什么?

例如,我有一个应用程序: - 打开日志文件 - 打开一些 USB 小工具 - 决定是时候关闭应用程序 - 调用 sys.exit(-1) - (或者它抛出严重的异常 - 但我更喜欢第一种方式,因为我有点小猪,代码的某些部分实际上捕获了所有异常,这将停止我的终止异常......)

然后我需要一些 finalize() 函数,在退出解释器之前肯定会调用它。Finalize() 将按此顺序释放 USB 小工具并关闭日志文件。

我尝试了 def del但它没有被 sys.exit 调用,而且我无法决定 _ del _s 的调用顺序。

对我有什么救赎吗?还是我必须这样做: 1. 最重要的 try-catch-finally 2. 退出是否带有一些特定的异常 3. 每个异常捕获的任何地方都准确地指定了我正在捕获的内容?

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 回答