Elliot Elliot - 1 year ago 88
Python Question

Multiple Try-Excepts followed by an Else in python

Is there some way to have several consecutive Try-Except clauses that trigger a single Else only if all of them are successful?

As an example:

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')
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')
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')
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')
private.logger.info('Meters initialized')

As you can see, you only want to print
meters initialized
if all of them went off, however as currently written it only depends on the heater thermometer. is there some way to stack these?

abc abc
Answer Source

You can keep a boolean, initialized at the beginning to: everythingOK=True Then set it to False in all the except blocks and log the final line only if true.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download