python中多个TryExcepts后跟一个Else

2024-10-03 11:21:33 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有什么方法可以让多个连续的Try除了只有在所有子句都成功的情况下才会触发单个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如果它们都熄灭了,但是正如目前所写的,它只取决于加热器温度计。有什么办法把这些叠起来吗?在


Tags: valueonaddressvisachannelnotlocationprivate
3条回答

就个人而言,我只需要一个trip变量init_ok或类似的东西。在

将其设置为True,并让所有except子句都将其设置为False,然后在最后进行测试?在

您可以保留一个在开头初始化的布尔值:everythingOK=True 然后在所有的except块中将其设置为False,并且只有在true时才记录最后一行。在

考虑将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')

相关问题 更多 >