2

I have a script for controlling some instruments during an experiment that looks like this:

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

If an Exception occurs inside the loop (e.g. some hardware problem for the camera or the stage), then I want to go save the results and close the instruments. If an Exception occurs before the loop, then I just want to close the instruments. How to do this? I can put many try/except statements, but are there other better methods?

Physicist
  • 2,848
  • 8
  • 33
  • 62
  • Possible duplicate of [Doing something before program exit](https://stackoverflow.com/questions/3850261/doing-something-before-program-exit) – Georgy Feb 08 '18 at 15:05

2 Answers2

2

You can use a try-finally statement.

camera = Camera()
stage = Stage()
try:
  # do stuff
finally:
  camera.close()
  stage.close()
internet_user
  • 3,149
  • 1
  • 20
  • 29
2

You have several options. You could register atexit handlers as needed (first, one that would close the instruments), then before the loop, one that would save results. Though, meh.

Using two 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()

Maybe:

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()
petre
  • 1,485
  • 14
  • 24