Several try-excepts followed by Else in python

Is there a way to have multiple consecutive Try-Except statements that run one Else only if all of them are successful?

As an example:

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

As you can see, you only want to print meters initialized if they all go out, however at the moment it depends only on the heater thermometer. is there any way to stack them?

+4
source share
5 answers

You can save the boolean initialized at the beginning so that: everythingOK=True Then set it to False in all other blocks and write the final line only if true.

+3
source

Consider splitting the try/except structure into a function that returns True if the call worked, and False if it failed, then use, for example, all() to ensure that they are all executed:

 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') 
+6
source

Personally, I just have the init_ok or somesuch disconnect variable.

Set it as True, and all the except clauses set to False, and then the test at the end?

+6
source

Try something like this. keeping the original behavior non-stop after the first exception

 success = True for meter, address, message in ( ('anodization_voltage_meter',voltage_meter_address,'Volt Meter is not on or not on this channel'), ('anodization_current_meter',current_meter_address,'Ammeter is not on or not on this channel'), ('sample_thermometer',sample_thermometer_address,'Sample Thermometer is not on or not on this channel'), ('heater_thermometer',heater_thermometer_address,'Heater Thermometer is not on or not on this channel')): try: setattr(private,meter, Voltmeter(address.value): except (visa.VisaIOError,): success = False private.logger.warning(message) if success: # everything is ok private.logger.info('Meters initialized') 
+6
source

You have several similar objects, and in such cases it is often better to treat them evenly and use a data-based approach.

So, I would start with your objects ..._meter_address . For me, they sound like a configuration for counters, so I will have a class that looks something like this:

 class MeterConfiguration(object): def __init__(self, name, address): self.name = name self.address = address def english_name(self): """A readable form of the name for this meter.""" return ' '.join(x.title() for x in self.name.split('_')) + ' Meter' 

Perhaps you have another configuration (currently stored in variables) that could also be here.

Then I will have a summary of all the counters that your program is associated with. I create them statically, but it is possible that you can read all or part of this information from the configuration file. I have no idea what your addresses look like, so I did something :)

 ALL_METERS = [ MeterConfiguration('anodization_voltage', 'PORT0001'), MeterConfiguration('anodization_current', 'PORT0002'), MeterConfiguration('sample_thermometer', 'PORT0003'), MeterConfiguration('heater_thermometer', 'PORT0004') ] 

Cool, now the whole configuration is in one place, and we can use this to make things the same and simpler.

 private.meters = {} any_errors = False for meter in ALL_METERS: try: private.meters[meter.name] = Voltmeter(meter.address) except VisaError: logging.error('%s not found at %s', meter.english_name(), meter.address) any_errors = True if not any_errors: logging.info('All meters initialized.') 

You can use, for example, private.meters['anodization_voltage'] to refer to a specific counter or private.meters['anodization_voltage'] over meters if you need to do something for them.

+2
source

Source: https://habr.com/ru/post/1300124/


All Articles