如果程序在 Python 3 中失败,则跳转到脚本末尾

Jumping to the end of the script if program fails in Python 3

我有一个脚本,用于在实验期间控制一些仪器,如下所示:

camera = Camera()
stage = Stage()
results = []
# loads of other initialization

for n in steps:
    stage.move(n)
    img = camera.capture()
    # loads of other function/method calls
    results.append(img)

results = np.array(results)
np.savetxt('data.txt',results)

camera.close()
stage.close()

如果循环内发生异常(例如相机或舞台的某些硬件问题),那么我想保存 results 并关闭仪器。如果在循环之前发生异常,那么我只想关闭仪器。这该怎么做?我可以放很多try/except语句,但是还有其他更好的方法吗?

您可以使用 try-finally 语句。

camera = Camera()
stage = Stage()
try:
  # do stuff
finally:
  camera.close()
  stage.close()

您有多种选择。您可以根据需要注册 atexit 处理程序(第一个,一个将关闭仪器),然后在循环之前,一个将保存结果。不过,嗯。

使用两个 try/except:

try:
    camera = Camera()
    stage = Stage()
    results = []
    # loads of other initialization

    try:
        for n in steps:
            stage.move(n)
            img = camera.capture()
            # loads of other function/method calls
            results.append(img)
    finally:
         results = np.array(results)
         np.savetxt('data.txt',results)
finally:
    camera.close()
    stage.close()

也许:

try:
    do_save = False
    camera = Camera()
    stage = Stage()
    results = []
    # loads of other initialization

    do_save = True
    for n in steps:
        stage.move(n)
        img = camera.capture()
        # loads of other function/method calls
        results.append(img)
finally:
    if do_save:
        results = np.array(results)
        np.savetxt('data.txt',results)
    camera.close()
    stage.close()