私はPythonでプロシージャを作成しています。このプロシージャは、基本的なレベルでモーターコントローラーと通信します。コントローラがエラーが発生したことを示すフラグをスローする可能性があります。私はこれらのエラーを最もよく処理する方法を見つけようとしています。
以下の例では、温度障害、電流制限障害、および電圧障害の3つのエラーが考えられます。私はそれらを別の方法で処理しました。正しい方法はありますか、それとも主観的ですか?
class motor_fault(Exception):
def __init__(self,error):
motor.move_at = 0 #Stop motor
self.error = error
def __str__(self):
return repr(self.value)
motor.velocity_limit = motor.slow
motor.velocity_limit_enable = True
try:
motor.move_to_absolute = motor.instrument_pos
while motor.in_position == 0:
if motor.current_limit == 1:
motor.move_at = 0 #Stop motor
print('Motor current error')
break
if motor.temp_fault == 1: raise motor_fault('Temperature Fault')
if motor.voltage_fault == 1: raise voltage_fault:
time.sleep(0.5)
else:
print('reached desired instrument position with no faults')
except motor_temp_fault as e:
#Not sure what I'd do here...
print('My exception occurred, value:', e.error)
pass
except:
motor.move_at = 0 #Stop motor just in case
print(' some other fault, probably voltage')
else:
print (' this is only printed if there were no errors')
finally:
print ('this is printed regardless of how the try exits')
全体を削除する方がはるかに簡単なようtry:
です。whileループにフラグを設定して中断するだけです。ループの後、フラグを見て、whileループが正常に終了したかどうかを確認します。
fault = False
while motor.in_position == 0:
if motor.current_limit == 1:
fault = 'Motor current error'
break
if motor.temp_fault == 1:
fault = 'Motor temperature error'
break
if motor.voltage_fault == 1:
fault = 'Motor voltage error'
break
time.sleep(0.5)
else:
print('reached waterline with no faults')
if fault:
motor.move_at = 0 #Stop motor
print(fault)
# Now look at the fault string to determine the next course of action.
しかし、それはどういうわけか、私が本当に理解していない用語を使用するのは間違っているか、非Python的であるように思われます。これには本当に何か問題がありますか?おかげで、私はCS専攻ではなく、1982年以来プログラミングクラスを受講していないことを覚えておいてください。