gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:52 25 4
gpt4 key购买 nike

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

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

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

最佳答案

您有多种选择。你可以注册 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()

关于python - 如果程序在 Python 3 中失败,则跳转到脚本末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48686529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com