timofurrer / w1thermsensor

A Python package and CLI tool to work with w1 temperature sensors like DS1822, DS18S20 & DS18B20 on the Raspberry Pi, Beagle Bone and other devices.
MIT License
493 stars 113 forks source link

Cannot catch KernelModuleLoadError #110

Open ggstuart opened 3 years ago

ggstuart commented 3 years ago

Hi, I was trying to catch the KernelModuleLoadError and handle it.

from w1thermsensor.errors import KernelModuleLoadError

However, its not possible to import the exception without raising the error.

This seems to be because your __init__.py module calls the load_kernel_modules() method immediately.

So its not possible to get a reference to the error without raising it first.

Any ideas about how I could work around this? Or ways to rearrange things?

timofurrer commented 3 years ago

indeed 🤦

Any ideas about how I could work around this? Or ways to rearrange things?

I don't think it'll be possible unless I move the auto-loading of the kernel module to w1thermsensor.core and don't import that in __init__.py - and with that basically making the user to import w1thermsensor manually. AFAIK there is no way to import something like w1thermsensor.error as module without the w1thermsensor/__init__.py being imported, too ...

As a work around you could disable the auto-loading and just call it yourself:

# set W1THERMSENSOR_NO_KERNEL_MODULE=1 in environment (either before launching your app or in the app)
from w1thermsensor import W1ThermSensor, load_kernel_modules, KernelModuleLoadError

try:
   load_kernel_modules()
except KernelModuleLoadError as exc:
   ...

Or you are basically fine with just catching it as Exception ... but I agree to your point that with that the KernelModuleLoadError is basically useless.

I'm open for suggestions.