Python中多个Try-Except后跟Else
有没有办法让多个连续的尝试-异常(Try-Except)语句只在它们全部成功时触发一个单独的“否则”(Else)呢?
举个例子:
try:
private.anodization_voltage_meter = Voltmeter(voltage_meter_address.value) #assign voltmeter location
except(visa.VisaIOError): #channel time out
private.logger.warning('Volt Meter is not on or not on this channel')
try:
private.anodization_current_meter = Voltmeter(current_meter_address.value) #assign voltmeter as current meter location
except(visa.VisaIOError): #channel time out
private.logger.warning('Ammeter is not on or not on this channel')
try:
private.sample_thermometer = Voltmeter(sample_thermometer_address.value)#assign voltmeter as thermomter location for sample.
except(visa.VisaIOError): #channel time out
private.logger.warning('Sample Thermometer is not on or not on this channel')
try:
private.heater_thermometer = Voltmeter(heater_thermometer_address.value)#assign voltmeter as thermomter location for heater.
except(visa.VisaIOError): #channel time out
private.logger.warning('Heater Thermometer is not on or not on this channel')
else:
private.logger.info('Meters initialized')
如你所见,只有在所有的尝试都成功时,才想打印出 meters initialized
,但目前的写法只依赖于加热器的温度计。有没有办法把这些语句叠加起来呢?
5 个回答
6
我个人建议可以用一个叫 init_ok
的变量来记录状态。
先把它设置为真(True),然后在所有的异常处理部分把它设置为假(False)。最后再检查这个变量的值就可以了。
6
可以考虑把 try/except
这个结构拆分成一个函数,这个函数如果调用成功就返回 True
,如果失败就返回 False
。然后可以使用比如 all()
这样的函数来检查它们是否都成功了:
def initfunc(structure, attrname, address, desc):
try:
var = Voltmeter(address.value)
setattr(structure, attrname, var)
return True
except(visa.VisaIOError):
structure.logger.warning('%s is not on or not on this channel' % (desc,))
if all([initfunc(*x) for x in [(private, 'anodization_voltage_meter', voltage_meter_address, 'Volt Meter'), ...]]):
private.logger.info('Meters initialized')
3
你可以先定义一个布尔值,刚开始的时候把它设置为:everythingOK=True
。然后在所有的异常处理块中把它改成False
。最后只有在这个值为真的时候,才记录最后一行信息。