Skip to content

Commit cee0c6d

Browse files
committed
use try: except
1 parent d7af388 commit cee0c6d

File tree

7 files changed

+75
-46
lines changed

7 files changed

+75
-46
lines changed

pyproject.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ readme = {file = ["README.md"], content-type = "text/markdown"}
2727

2828
[project.optional-dependencies]
2929
tests = ["pytest"]
30-
lint = ["flake8", "flake8-bugbear", "flake8-builtins", "flake8-blind-except", "mypy"]
30+
lint = ["flake8", "flake8-bugbear", "flake8-builtins", "flake8-blind-except",
31+
"mypy", "types-requests"]
3132

3233
[tool.black]
3334
line-length = 100

src/mozloc/__main__.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,21 @@
1515
p = argparse.ArgumentParser()
1616
p.add_argument("logfile", help="logfile to append location to", nargs="?")
1717
p.add_argument(
18-
"-T", "--cadence", help="how often to update [sec]. Some laptops cannot go faster than 30 sec.", default=60, type=float
18+
"-T",
19+
"--cadence",
20+
help="how often to update [sec]. Some laptops cannot go faster than 30 sec.",
21+
default=60,
22+
type=float,
1923
)
2024
p.add_argument(
2125
"-url",
2226
help="Mozilla location services URL--don't use this default test key",
2327
default="https://location.services.mozilla.com/v1/geolocate?key=test",
2428
)
2529
p.add_argument("-i", "--infile", help="use raw text saved from command line")
26-
p = p.parse_args()
30+
args = p.parse_args()
2731

28-
if p.infile:
29-
process_file(p.infile, mozilla_url=p.url)
32+
if args.infile:
33+
process_file(args.infile, mozilla_url=args.url)
3034
else:
31-
log_wifi_loc(cadence_sec=p.cadence, mozilla_url=p.url, logfile=p.logfile)
35+
log_wifi_loc(cadence_sec=args.cadence, mozilla_url=args.url, logfile=args.logfile)

src/mozloc/airport.py

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,25 @@
77
import subprocess
88
import re
99

10-
EXE = shutil.which("airport", path="/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources")
10+
EXE = shutil.which(
11+
"airport",
12+
path="/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources",
13+
)
1114
if not EXE:
1215
raise ImportError("Could not find Airport")
1316

1417

1518
def cli_config_check() -> bool:
1619
# %% check that Airport is available and WiFi is active
17-
ret = subprocess.run([EXE, "--getinfo"], stdout=subprocess.PIPE, text=True, timeout=30)
1820

19-
if ret.returncode != 0:
21+
assert isinstance(EXE, str)
22+
try:
23+
ret = subprocess.check_output([EXE, "--getinfo"], text=True, timeout=30)
24+
except subprocess.CalledProcessError as err:
25+
logging.error(err)
2026
return False
2127

22-
stdout = ret.stdout.strip().lower()
28+
stdout = ret.strip().lower()
2329
if len(stdout) == "airport: off":
2430
return False
2531

@@ -32,12 +38,13 @@ def cli_config_check() -> bool:
3238

3339
def get_signal() -> str:
3440

35-
ret = subprocess.run([EXE, "-s"], timeout=30.0, stdout=subprocess.PIPE, text=True)
41+
assert isinstance(EXE, str)
42+
try:
43+
ret = subprocess.check_output([EXE, "-s"], text=True, timeout=30.0)
44+
except subprocess.CalledProcessError as err:
45+
logging.error(f"consider slowing scan cadence. {err}")
3646

37-
if ret.returncode != 0:
38-
logging.error("consider slowing scan cadence.")
39-
40-
return ret.stdout
47+
return ret
4148

4249

4350
def parse_signal(raw: str) -> list[dict[str, T.Any]]:

src/mozloc/base.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import annotations
12
from time import sleep
23
from pathlib import Path
34
import logging
@@ -24,7 +25,7 @@ def process_file(file: Path, mozilla_url: str):
2425
print(stat)
2526

2627

27-
def log_wifi_loc(cadence_sec: float, mozilla_url: str, logfile: Path = None):
28+
def log_wifi_loc(cadence_sec: float, mozilla_url: str, logfile: Path | None = None):
2829

2930
if logfile:
3031
logfile = Path(logfile).expanduser()

src/mozloc/csv2kml/__main__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@
77
p = argparse.ArgumentParser()
88
p.add_argument("logfn", help="csv logfile to read")
99
p.add_argument("kmlfn", help="kml filename to write")
10-
p = p.parse_args()
10+
args = p.parse_args()
1111

12-
csv2kml(p.logfn, p.kmlfn)
12+
csv2kml(args.logfn, args.kmlfn)

src/mozloc/netman.py

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,26 @@
99
import io
1010
from time import sleep
1111

12-
NMCLI = shutil.which("nmcli")
13-
if not NMCLI:
12+
EXE = shutil.which("nmcli")
13+
if not EXE:
1414
raise ImportError('Could not find NetworkManager "nmcli"')
1515

16-
NMCMD = [NMCLI, "-g", "SSID,BSSID,FREQ,SIGNAL", "device", "wifi"] # Debian stretch, Ubuntu 18.04
17-
NMLEG = [NMCLI, "-t", "-f", "SSID,BSSID,FREQ,SIGNAL", "device", "wifi"] # ubuntu 16.04
18-
NMSCAN = [NMCLI, "device", "wifi", "rescan"]
16+
NMCMD = [EXE, "-g", "SSID,BSSID,FREQ,SIGNAL", "device", "wifi"] # Debian stretch, Ubuntu 18.04
17+
NMLEG = [EXE, "-t", "-f", "SSID,BSSID,FREQ,SIGNAL", "device", "wifi"] # ubuntu 16.04
18+
NMSCAN = [EXE, "device", "wifi", "rescan"]
1919

2020

2121
def cli_config_check() -> bool:
2222
# %% check that NetworkManager CLI is available and WiFi is active
23-
ret = subprocess.run([NMCLI, "-t", "radio", "wifi"], stdout=subprocess.PIPE, text=True, timeout=2)
2423

25-
if ret.returncode != 0:
24+
assert isinstance(EXE, str)
25+
try:
26+
ret = subprocess.check_output([EXE, "-t", "radio", "wifi"], text=True, timeout=2)
27+
except subprocess.CalledProcessError as err:
28+
logging.error(err)
2629
return False
2730

28-
stdout = ret.stdout.strip().split(":")
31+
stdout = ret.strip().split(":")
2932
if "enabled" in stdout:
3033
return True
3134

@@ -42,16 +45,19 @@ def cli_config_check() -> bool:
4245

4346
def get_signal() -> str:
4447

45-
ret = subprocess.run(NMCMD, timeout=1.0)
46-
if ret.returncode != 0:
47-
raise ConnectionError("could not connect with NetworkManager for WiFi")
48+
try:
49+
subprocess.check_call(NMCMD, timeout=1.0)
50+
except subprocess.CalledProcessError as err:
51+
raise ConnectionError(f"could not connect with NetworkManager for WiFi {err}")
52+
4853
sleep(0.5) # nmcli errored for less than about 0.2 sec.
4954
# takes several seconds to update, so do it now.
50-
ret = subprocess.run(NMSCAN, timeout=1.0, stdout=subprocess.PIPE, text=True)
51-
if ret.returncode != 0:
52-
logging.error("consider slowing scan cadence.")
55+
try:
56+
ret = subprocess.check_output(NMSCAN, timeout=1.0, text=True)
57+
except subprocess.CalledProcessError as err:
58+
logging.error(f"consider slowing scan cadence. {err}")
5359

54-
return ret.stdout
60+
return ret
5561

5662

5763
def parse_signal(raw: str) -> list[dict[str, T.Any]]:

src/mozloc/netsh.py

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,28 @@
77
import io
88
import shutil
99

10-
CLI = shutil.which("netsh")
11-
if not CLI:
10+
EXE = shutil.which("netsh")
11+
if not EXE:
1212
raise ImportError('Could not find NetSH "netsh"')
1313

14-
CMD = [CLI, "wlan", "show", "networks", "mode=bssid"]
14+
CMD = [EXE, "wlan", "show", "networks", "mode=bssid"]
1515

1616

1717
def cli_config_check() -> bool:
18-
# %% check that NetSH CLI is available and WiFi is active
19-
ret = subprocess.run(CMD, stdout=subprocess.PIPE, text=True, timeout=2)
20-
for line in ret.stdout.split("\n"):
18+
# %% check that NetSH EXE is available and WiFi is active
19+
try:
20+
ret = subprocess.check_output(CMD, text=True, timeout=2)
21+
except subprocess.CalledProcessError as err:
22+
logging.error(err)
23+
return False
24+
25+
for line in ret.split("\n"):
2126
if "networks currently visible" in line:
2227
return True
23-
if "The wireless local area network interface is powered down and doesn't support the requested operation" in line:
28+
if (
29+
"The wireless local area network interface is powered down and doesn't support the requested operation"
30+
in line
31+
):
2432
logging.error("must enable WiFi, it appears to be turned off.")
2533
return False
2634

@@ -30,15 +38,17 @@ def cli_config_check() -> bool:
3038

3139
def get_signal() -> str:
3240
"""
33-
get signal strength using CLI
41+
get signal strength using EXE
3442
35-
returns dict of data parsed from CLI
43+
returns dict of data parsed from EXE
3644
"""
37-
ret = subprocess.run(CMD, timeout=1.0, stdout=subprocess.PIPE, text=True)
38-
if ret.returncode != 0:
39-
logging.error("consider slowing scan cadence.")
4045

41-
return ret.stdout
46+
try:
47+
ret = subprocess.check_output(CMD, timeout=1.0, text=True)
48+
except subprocess.CalledProcessError as err:
49+
logging.error(f"consider slowing scan cadence. {err}")
50+
51+
return ret
4252

4353

4454
def parse_signal(raw: str) -> list[dict[str, T.Any]]:

0 commit comments

Comments
 (0)