Skip to content

Commit 8fc1b62

Browse files
committed
cleanups in socketcan helpers
1 parent 01e8c87 commit 8fc1b62

2 files changed

Lines changed: 10 additions & 18 deletions

File tree

can/interfaces/socketcan/utils.py

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,16 @@
22
Defines common socketcan functions.
33
"""
44

5-
from typing import cast, Iterable, Optional
6-
import can.typechecking as typechecking
7-
85
import logging
96
import os
107
import errno
118
import struct
129
import subprocess
1310
import re
11+
from typing import cast, Iterable, Optional
1412

1513
from can.interfaces.socketcan.constants import CAN_EFF_FLAG
14+
import can.typechecking as typechecking
1615

1716
log = logging.getLogger(__name__)
1817

@@ -49,11 +48,11 @@ def find_available_interfaces() -> Iterable[str]:
4948
"""
5049

5150
try:
52-
# it might be good to add "type vcan", but that might (?) exclude physical can devices
51+
# adding "type vcan" would exclude physical can devices
5352
command = ["ip", "-o", "link", "list", "up"]
5453
output = subprocess.check_output(command, universal_newlines=True)
5554

56-
except Exception as e: # subprocess.CalledProcessError was too specific
55+
except Exception as e: # subprocess.CalledProcessError is too specific
5756
log.error("failed to fetch opened can devices: %s", e)
5857
return []
5958

@@ -66,23 +65,15 @@ def find_available_interfaces() -> Iterable[str]:
6665
return filter(_PATTERN_CAN_INTERFACE.match, interface_names)
6766

6867

69-
def error_code_to_str(code: int) -> str:
68+
def error_code_to_str(code: Optional[int]) -> str:
7069
"""
7170
Converts a given error code (errno) to a useful and human readable string.
7271
7372
:param code: a possibly invalid/unknown error code
7473
:returns: a string explaining and containing the given error code, or a string
7574
explaining that the errorcode is unknown if that is the case
7675
"""
76+
name = errno.errorcode.get(code, "UNKNOWN")
77+
description = os.strerror(code)
7778

78-
try:
79-
name = errno.errorcode[code]
80-
except KeyError:
81-
name = "UNKNOWN"
82-
83-
try:
84-
description = os.strerror(code)
85-
except ValueError:
86-
description = "no description available"
87-
88-
return "{} (errno {}): {}".format(name, code, description)
79+
return f"{name} (errno {code}): {description}"

test/test_socketcan_helpers.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,11 @@
99

1010
from can.interfaces.socketcan.utils import find_available_interfaces, error_code_to_str
1111

12-
from .config import *
12+
from .config import IS_LINUX, TEST_INTERFACE_SOCKETCAN
1313

1414

1515
class TestSocketCanHelpers(unittest.TestCase):
16+
1617
@unittest.skipUnless(IS_LINUX, "socketcan is only available on Linux")
1718
def test_error_code_to_str(self):
1819
"""

0 commit comments

Comments
 (0)