From 01855da9158495c1240ba28d5a81f9f26472c81e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 9 Sep 2021 16:13:31 +0200 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Make=20py2=20compatible=20?= =?UTF-8?q?&=20internalize=20search?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We only use the search in one single place, it's not part of an external API and three lines only. It makes sense to internalize it into serialList. Also, python 2 doesn't yet have os.scandir, so use the fallback implementation in that case. --- src/octoprint/util/comm.py | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index c4f0f5d6e..eb1e909f3 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -24,6 +24,11 @@ try: except ImportError: import Queue as queue +try: + from os import scandir +except ImportError: + from scandir import scandir + import logging from collections import deque @@ -192,22 +197,6 @@ regex_serial_devices = re.compile(r"^(?:ttyUSB|ttyACM|tty\.usb|cu\.|cuaU|ttyS|rf """Regex used to filter out valid tty devices""" -def _searchFiles(directory, pattern): - """ - Searches the directory for files matching the regex pattern - - We could use glob, but that might require multiple glob executions (and - multiple directory file listings), which can end up being slow on the - low-end devices we support. - """ - result = [] - with os.scandir(directory) as it: - for entry in it: - if pattern.match(entry.name): - result.append(entry.path) - return result - - def serialList(): if os.name == "nt": candidates = [] @@ -223,7 +212,11 @@ def serialList(): pass else: - candidates = _searchFiles("/dev", regex_serial_devices) + candidates = [] + with scandir("/dev") as it: + for entry in it: + if regex_serial_devices.match(entry.name): + candidates.append(entry.path) # additional ports additionalPorts = settings().get(["serial", "additionalPorts"])