refactor: Use f-strings for more exceptions and log message
Semi manually convert remaining strings with no translation to f-string.
This commit is contained in:
parent
d1d3d71091
commit
4e6361429e
|
@ -397,7 +397,7 @@ def write(device_handle, data):
|
||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
if bytes_written != len(data):
|
if bytes_written != len(data):
|
||||||
raise OSError(_errno.EIO, "written %d bytes out of expected %d" % (bytes_written, len(data)))
|
raise OSError(_errno.EIO, f"written {int(bytes_written)} bytes out of expected {len(data)}")
|
||||||
|
|
||||||
|
|
||||||
def read(device_handle, bytes_count, timeout_ms=-1):
|
def read(device_handle, bytes_count, timeout_ms=-1):
|
||||||
|
@ -422,7 +422,7 @@ def read(device_handle, bytes_count, timeout_ms=-1):
|
||||||
|
|
||||||
if xlist:
|
if xlist:
|
||||||
assert xlist == [device_handle]
|
assert xlist == [device_handle]
|
||||||
raise OSError(_errno.EIO, "exception on file descriptor %d" % device_handle)
|
raise OSError(_errno.EIO, f"exception on file descriptor {int(device_handle)}")
|
||||||
|
|
||||||
if rlist:
|
if rlist:
|
||||||
assert rlist == [device_handle]
|
assert rlist == [device_handle]
|
||||||
|
|
|
@ -345,7 +345,7 @@ class NamedInt(int):
|
||||||
return self.name
|
return self.name
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return "NamedInt(%d, %r)" % (int(self), self.name)
|
return f"NamedInt({int(self)}, {self.name!r})"
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_yaml(cls, loader, node):
|
def from_yaml(cls, loader, node):
|
||||||
|
@ -475,9 +475,9 @@ class NamedInts:
|
||||||
raise TypeError("name must be a string")
|
raise TypeError("name must be a string")
|
||||||
|
|
||||||
if str(value) in self.__dict__:
|
if str(value) in self.__dict__:
|
||||||
raise ValueError("%s (%d) already known" % (value, int(value)))
|
raise ValueError(f"{value} ({int(int(value))}) already known")
|
||||||
if int(value) in self._indexed:
|
if int(value) in self._indexed:
|
||||||
raise ValueError("%d (%s) already known" % (int(value), value))
|
raise ValueError(f"{int(int(value))} ({value}) already known")
|
||||||
|
|
||||||
self._values.append(value)
|
self._values.append(value)
|
||||||
self._is_sorted = False
|
self._is_sorted = False
|
||||||
|
|
|
@ -542,7 +542,7 @@ class Device:
|
||||||
name = self._name or self._codename or "?"
|
name = self._name or self._codename or "?"
|
||||||
except exceptions.NoSuchDevice:
|
except exceptions.NoSuchDevice:
|
||||||
name = "name not available"
|
name = "name not available"
|
||||||
return "<Device(%d,%s,%s,%s)>" % (self.number, self.wpid or self.product_id, name, self.serial)
|
return f"<Device({int(self.number)},{self.wpid or self.product_id},{name},{self.serial})>"
|
||||||
|
|
||||||
__repr__ = __str__
|
__repr__ = __str__
|
||||||
|
|
||||||
|
|
|
@ -1266,11 +1266,11 @@ class MouseClick(Action):
|
||||||
self.count = 1
|
self.count = 1
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return "MouseClick: %s (%d)" % (self.button, self.count)
|
return f"MouseClick: {self.button} ({int(self.count)})"
|
||||||
|
|
||||||
def evaluate(self, feature, notification, device, last_result):
|
def evaluate(self, feature, notification, device, last_result):
|
||||||
if logger.isEnabledFor(logging.INFO):
|
if logger.isEnabledFor(logging.INFO):
|
||||||
logger.info("MouseClick action: %d %s" % (self.count, self.button))
|
logger.info(f"MouseClick action: {int(self.count)} {self.button}")
|
||||||
if self.button and self.count:
|
if self.button and self.count:
|
||||||
click(buttons[self.button], self.count)
|
click(buttons[self.button], self.count)
|
||||||
_time.sleep(0.01)
|
_time.sleep(0.01)
|
||||||
|
|
|
@ -203,7 +203,7 @@ class Receiver:
|
||||||
|
|
||||||
def register_new_device(self, number, notification=None):
|
def register_new_device(self, number, notification=None):
|
||||||
if self._devices.get(number) is not None:
|
if self._devices.get(number) is not None:
|
||||||
raise IndexError("%s: device number %d already registered" % (self, number))
|
raise IndexError(f"{self}: device number {int(number)} already registered")
|
||||||
|
|
||||||
assert notification is None or notification.devnumber == number
|
assert notification is None or notification.devnumber == number
|
||||||
assert notification is None or notification.sub_id == 0x41
|
assert notification is None or notification.sub_id == 0x41
|
||||||
|
|
|
@ -773,7 +773,7 @@ class DpiSlidingXY(_RawXYProcessing):
|
||||||
|
|
||||||
def displayNewDpi(self, newDpiIdx):
|
def displayNewDpi(self, newDpiIdx):
|
||||||
if _notify.available:
|
if _notify.available:
|
||||||
reason = "DPI %d [min %d, max %d]" % (self.dpiChoices[newDpiIdx], self.dpiChoices[0], self.dpiChoices[-1])
|
reason = f"DPI {int(self.dpiChoices[newDpiIdx])} [min {int(self.dpiChoices[0])}, max {int(self.dpiChoices[-1])}]"
|
||||||
_notify.show(self.device, reason)
|
_notify.show(self.device, reason)
|
||||||
|
|
||||||
def press_action(self, key): # start tracking
|
def press_action(self, key): # start tracking
|
||||||
|
|
|
@ -221,6 +221,6 @@ def run(cli_args=None, hidraw_path=None):
|
||||||
m.run(c, args, _find_receiver, _find_device)
|
m.run(c, args, _find_receiver, _find_device)
|
||||||
except AssertionError:
|
except AssertionError:
|
||||||
tb_last = extract_tb(_sys.exc_info()[2])[-1]
|
tb_last = extract_tb(_sys.exc_info()[2])[-1]
|
||||||
_sys.exit("%s: assertion failed: %s line %d" % (NAME.lower(), tb_last[0], tb_last[1]))
|
_sys.exit(f"{NAME.lower()}: assertion failed: {tb_last[0]} line {int(tb_last[1])}")
|
||||||
except Exception:
|
except Exception:
|
||||||
_sys.exit(f"{NAME.lower()}: error: {format_exc()}")
|
_sys.exit(f"{NAME.lower()}: error: {format_exc()}")
|
||||||
|
|
|
@ -127,7 +127,7 @@ def run(receivers, args, find_receiver, _ignore):
|
||||||
|
|
||||||
if receiver.pairing.new_device:
|
if receiver.pairing.new_device:
|
||||||
dev = receiver.pairing.new_device
|
dev = receiver.pairing.new_device
|
||||||
print("Paired device %d: %s (%s) [%s:%s]" % (dev.number, dev.name, dev.codename, dev.wpid, dev.serial))
|
print(f"Paired device {int(dev.number)}: {dev.name} ({dev.codename}) [{dev.wpid}:{dev.serial}]")
|
||||||
else:
|
else:
|
||||||
error = receiver.pairing.error
|
error = receiver.pairing.error
|
||||||
if error:
|
if error:
|
||||||
|
|
|
@ -45,9 +45,9 @@ def _print_receiver(receiver):
|
||||||
for f in receiver.firmware:
|
for f in receiver.firmware:
|
||||||
print(" %-11s: %s" % (f.kind, f.version))
|
print(" %-11s: %s" % (f.kind, f.version))
|
||||||
|
|
||||||
print(" Has", paired_count, "paired device(s) out of a maximum of %d." % receiver.max_devices)
|
print(" Has", paired_count, f"paired device(s) out of a maximum of {int(receiver.max_devices)}.")
|
||||||
if receiver.remaining_pairings() and receiver.remaining_pairings() >= 0:
|
if receiver.remaining_pairings() and receiver.remaining_pairings() >= 0:
|
||||||
print(" Has %d successful pairing(s) remaining." % receiver.remaining_pairings())
|
print(f" Has {int(receiver.remaining_pairings())} successful pairing(s) remaining.")
|
||||||
|
|
||||||
notification_flags = _hidpp10.get_notification_flags(receiver)
|
notification_flags = _hidpp10.get_notification_flags(receiver)
|
||||||
if notification_flags is not None:
|
if notification_flags is not None:
|
||||||
|
@ -60,7 +60,7 @@ def _print_receiver(receiver):
|
||||||
activity = receiver.read_register(_hidpp10_constants.REGISTERS.devices_activity)
|
activity = receiver.read_register(_hidpp10_constants.REGISTERS.devices_activity)
|
||||||
if activity:
|
if activity:
|
||||||
activity = [(d, ord(activity[d - 1 : d])) for d in range(1, receiver.max_devices)]
|
activity = [(d, ord(activity[d - 1 : d])) for d in range(1, receiver.max_devices)]
|
||||||
activity_text = ", ".join(("%d=%d" % (d, a)) for d, a in activity if a > 0)
|
activity_text = ", ".join(f"{int(d)}={int(a)}" for d, a in activity if a > 0)
|
||||||
print(" Device activity counters:", activity_text or "(empty)")
|
print(" Device activity counters:", activity_text or "(empty)")
|
||||||
|
|
||||||
|
|
||||||
|
@ -70,7 +70,7 @@ def _battery_text(level):
|
||||||
elif isinstance(level, _NamedInt):
|
elif isinstance(level, _NamedInt):
|
||||||
return str(level)
|
return str(level)
|
||||||
else:
|
else:
|
||||||
return "%d%%" % level
|
return f"{int(level)}%"
|
||||||
|
|
||||||
|
|
||||||
def _battery_line(dev):
|
def _battery_line(dev):
|
||||||
|
@ -96,7 +96,7 @@ def _print_device(dev, num=None):
|
||||||
return
|
return
|
||||||
|
|
||||||
if num or dev.number < 8:
|
if num or dev.number < 8:
|
||||||
print(" %d: %s" % (num or dev.number, dev.name))
|
print(f" {int(num or dev.number)}: {dev.name}")
|
||||||
else:
|
else:
|
||||||
print(f"{dev.name}")
|
print(f"{dev.name}")
|
||||||
print(" Device path :", dev.path)
|
print(" Device path :", dev.path)
|
||||||
|
@ -119,7 +119,7 @@ def _print_device(dev, num=None):
|
||||||
print(" Unit ID: ", dev.unitId)
|
print(" Unit ID: ", dev.unitId)
|
||||||
if dev.firmware:
|
if dev.firmware:
|
||||||
for fw in dev.firmware:
|
for fw in dev.firmware:
|
||||||
print(" %11s:" % fw.kind, (fw.name + " " + fw.version).strip())
|
print(f" {fw.kind:11}:", (fw.name + " " + fw.version).strip())
|
||||||
|
|
||||||
if dev.power_switch_location:
|
if dev.power_switch_location:
|
||||||
print(f" The power switch is located on the {dev.power_switch_location}.")
|
print(f" The power switch is located on the {dev.power_switch_location}.")
|
||||||
|
@ -235,7 +235,7 @@ def _print_device(dev, num=None):
|
||||||
response = dev.feature_request(_hidpp20_constants.FEATURE.CONFIG_CHANGE, 0x00)
|
response = dev.feature_request(_hidpp20_constants.FEATURE.CONFIG_CHANGE, 0x00)
|
||||||
print(f" Configuration: {response.hex()}")
|
print(f" Configuration: {response.hex()}")
|
||||||
elif feature == _hidpp20_constants.FEATURE.REMAINING_PAIRING:
|
elif feature == _hidpp20_constants.FEATURE.REMAINING_PAIRING:
|
||||||
print(" Remaining Pairings: %d" % _hidpp20.get_remaining_pairing(dev))
|
print(f" Remaining Pairings: {int(_hidpp20.get_remaining_pairing(dev))}")
|
||||||
elif feature == _hidpp20_constants.FEATURE.ONBOARD_PROFILES:
|
elif feature == _hidpp20_constants.FEATURE.ONBOARD_PROFILES:
|
||||||
if _hidpp20.get_onboard_mode(dev) == _hidpp20_constants.ONBOARD_MODES.MODE_HOST:
|
if _hidpp20.get_onboard_mode(dev) == _hidpp20_constants.ONBOARD_MODES.MODE_HOST:
|
||||||
mode = "Host"
|
mode = "Host"
|
||||||
|
@ -272,7 +272,7 @@ def _print_device(dev, num=None):
|
||||||
print(" %2d: %-26s, default: %-27s => %-26s" % (k.index, k.key, k.default_task, k.mapped_to))
|
print(" %2d: %-26s, default: %-27s => %-26s" % (k.index, k.key, k.default_task, k.mapped_to))
|
||||||
gmask_fmt = ",".join(k.group_mask)
|
gmask_fmt = ",".join(k.group_mask)
|
||||||
gmask_fmt = gmask_fmt if gmask_fmt else "empty"
|
gmask_fmt = gmask_fmt if gmask_fmt else "empty"
|
||||||
print(" %s, pos:%d, group:%1d, group mask:%s" % (", ".join(k.flags), k.pos, k.group, gmask_fmt))
|
print(f" {', '.join(k.flags)}, pos:{int(k.pos)}, group:{int(k.group):1}, group mask:{gmask_fmt}")
|
||||||
report_fmt = ", ".join(k.mapping_flags)
|
report_fmt = ", ".join(k.mapping_flags)
|
||||||
report_fmt = report_fmt if report_fmt else "default"
|
report_fmt = report_fmt if report_fmt else "default"
|
||||||
print(f" reporting: {report_fmt}")
|
print(f" reporting: {report_fmt}")
|
||||||
|
|
|
@ -33,6 +33,6 @@ def run(receivers, args, find_receiver, find_device):
|
||||||
# query these now, it's last chance to get them
|
# query these now, it's last chance to get them
|
||||||
number, codename, wpid, serial = dev.number, dev.codename, dev.wpid, dev.serial
|
number, codename, wpid, serial = dev.number, dev.codename, dev.wpid, dev.serial
|
||||||
dev.receiver._unpair_device(number, True) # force an unpair
|
dev.receiver._unpair_device(number, True) # force an unpair
|
||||||
print("Unpaired %d: %s (%s) [%s:%s]" % (number, dev.name, codename, wpid, serial))
|
print(f"Unpaired {int(number)}: {dev.name} ({codename}) [{wpid}:{serial}]")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise e
|
raise e
|
||||||
|
|
|
@ -85,7 +85,7 @@ def _battery_icon_name(level, charging):
|
||||||
def lux(level=None):
|
def lux(level=None):
|
||||||
if level is None or level < 0:
|
if level is None or level < 0:
|
||||||
return "light_unknown"
|
return "light_unknown"
|
||||||
return "solaar-light_%03d" % (20 * ((level + 50) // 100))
|
return f"solaar-light_{int(20 * ((level + 50) // 100)):03}"
|
||||||
|
|
||||||
|
|
||||||
_ICON_SETS = {}
|
_ICON_SETS = {}
|
||||||
|
|
|
@ -555,7 +555,7 @@ def _update_details(button):
|
||||||
flag_names = (
|
flag_names = (
|
||||||
(f"({_('none')})",) if flag_bits == 0 else _hidpp10_constants.NOTIFICATION_FLAG.flag_names(flag_bits)
|
(f"({_('none')})",) if flag_bits == 0 else _hidpp10_constants.NOTIFICATION_FLAG.flag_names(flag_bits)
|
||||||
)
|
)
|
||||||
yield (_("Notifications"), ("\n%15s" % " ").join(flag_names))
|
yield (_("Notifications"), (f"\n{' ':15}").join(flag_names))
|
||||||
|
|
||||||
def _set_details(text):
|
def _set_details(text):
|
||||||
_details._text.set_markup(text)
|
_details._text.set_markup(text)
|
||||||
|
@ -677,7 +677,7 @@ def _update_device_panel(device, panel, buttons, full=False):
|
||||||
|
|
||||||
if battery_voltage is not None:
|
if battery_voltage is not None:
|
||||||
panel._battery._label.set_text(_("Battery Voltage"))
|
panel._battery._label.set_text(_("Battery Voltage"))
|
||||||
text = "%dmV" % battery_voltage
|
text = f"{int(battery_voltage)}mV"
|
||||||
tooltip_text = _("Voltage reported by battery")
|
tooltip_text = _("Voltage reported by battery")
|
||||||
else:
|
else:
|
||||||
panel._battery._label.set_text(_("Battery Level"))
|
panel._battery._label.set_text(_("Battery Level"))
|
||||||
|
@ -686,12 +686,12 @@ def _update_device_panel(device, panel, buttons, full=False):
|
||||||
if battery_voltage is not None and battery_level is not None:
|
if battery_voltage is not None and battery_level is not None:
|
||||||
text += ", "
|
text += ", "
|
||||||
if battery_level is not None:
|
if battery_level is not None:
|
||||||
text += _(str(battery_level)) if isinstance(battery_level, _NamedInt) else "%d%%" % battery_level
|
text += _(str(battery_level)) if isinstance(battery_level, _NamedInt) else f"{int(battery_level)}%"
|
||||||
if battery_next_level is not None and not charging:
|
if battery_next_level is not None and not charging:
|
||||||
if isinstance(battery_next_level, _NamedInt):
|
if isinstance(battery_next_level, _NamedInt):
|
||||||
text += "<small> (" + _("next reported ") + _(str(battery_next_level)) + ")</small>"
|
text += "<small> (" + _("next reported ") + _(str(battery_next_level)) + ")</small>"
|
||||||
else:
|
else:
|
||||||
text += "<small> (" + _("next reported ") + ("%d%%" % battery_next_level) + ")</small>"
|
text += "<small> (" + _("next reported ") + f"{int(battery_next_level)}%" + ")</small>"
|
||||||
tooltip_text = tooltip_text + _(" and next level to be reported.")
|
tooltip_text = tooltip_text + _(" and next level to be reported.")
|
||||||
if is_online:
|
if is_online:
|
||||||
if charging:
|
if charging:
|
||||||
|
@ -889,11 +889,11 @@ def update_device(device, item, selected_device_id, need_popup, full=False):
|
||||||
_model.set_value(item, _COLUMN.STATUS_ICON, _CAN_SET_ROW_NONE)
|
_model.set_value(item, _COLUMN.STATUS_ICON, _CAN_SET_ROW_NONE)
|
||||||
else:
|
else:
|
||||||
if battery_voltage is not None and False: # Use levels instead of voltage here
|
if battery_voltage is not None and False: # Use levels instead of voltage here
|
||||||
status_text = "%(battery_voltage)dmV" % {"battery_voltage": battery_voltage}
|
status_text = f"{int(battery_voltage)}mV"
|
||||||
elif isinstance(battery_level, _NamedInt):
|
elif isinstance(battery_level, _NamedInt):
|
||||||
status_text = _(str(battery_level))
|
status_text = _(str(battery_level))
|
||||||
else:
|
else:
|
||||||
status_text = "%(battery_percent)d%%" % {"battery_percent": battery_level}
|
status_text = f"{int(battery_level)}%"
|
||||||
_model.set_value(item, _COLUMN.STATUS_TEXT, status_text)
|
_model.set_value(item, _COLUMN.STATUS_TEXT, status_text)
|
||||||
|
|
||||||
charging = device.battery_info.charging() if device.battery_info is not None else None
|
charging = device.battery_info.charging() if device.battery_info is not None else None
|
||||||
|
|
Loading…
Reference in New Issue