Skip to content

Commit 6fd1f79

Browse files
authored
Ensure files are always closed (#73)
This silences some warnings emitted from the tests, and it's just good practise anyway.
1 parent 85a72f1 commit 6fd1f79

File tree

15 files changed

+192
-176
lines changed

15 files changed

+192
-176
lines changed

generate_icons.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,8 @@ def recolor(tree, add) -> None:
8383
ET.register_namespace("","http://www.w3.org/2000/svg")
8484
for tp in ("sc", "scbt", "fake", "ds4", "hid", "rpad"):
8585
# Read svg and parse it
86-
data = open(f"{CICONS}{tp}-0.svg", "r").read()
86+
with open(f"{CICONS}{tp}-0.svg", "r") as file:
87+
data = file.read()
8788
# Create recolored images
8889
for key in RECOLORS:
8990
tree = ET.fromstring(data)

scc/cheader.py

Lines changed: 83 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -82,108 +82,109 @@ def defines(base, include):
8282
fname = os.path.normpath(os.path.abspath(os.path.join(base, include)))
8383
parsed.add(fname)
8484

85-
lexer = shlex.shlex(open(fname), posix=True)
85+
with open(fname) as file:
86+
lexer = shlex.shlex(file, posix=True)
8687

87-
lexer.whitespace = ' \t\r'
88-
lexer.commenters = ''
89-
lexer.quotes = '"'
88+
lexer.whitespace = ' \t\r'
89+
lexer.commenters = ''
90+
lexer.quotes = '"'
9091

91-
out = OrderedDict()
92+
out = OrderedDict()
9293

93-
def parse_c_comments(lexer, tok, ntok):
94-
if tok != '/' or ntok != '*':
95-
return False
96-
quotes = lexer.quotes
97-
lexer.quotes = ''
98-
while True:
99-
tok = lexer.get_token()
100-
ntok = lexer.get_token()
101-
if tok == '*' and ntok == '/':
102-
lexer.quotes = quotes
103-
break
104-
else:
105-
lexer.push_token(ntok)
106-
return True
107-
108-
def parse_cpp_comments(lexer, tok, ntok):
109-
if tok != '/' or ntok != '/':
110-
return False
111-
quotes = lexer.quotes
112-
lexer.quotes = ''
113-
while True:
114-
tok = lexer.get_token()
115-
if tok == '\n':
116-
lexer.quotes = quotes
117-
lexer.push_token(tok)
118-
break
119-
return True
120-
121-
while True:
122-
tok = lexer.get_token()
123-
if not tok or tok == '':
124-
break
125-
ntok = lexer.get_token()
126-
127-
if parse_c_comments(lexer, tok, ntok):
128-
continue
129-
if parse_cpp_comments(lexer, tok, ntok):
130-
continue
131-
132-
if tok != '\n' or ntok != '#':
133-
lexer.push_token(ntok)
134-
continue
135-
136-
tok = lexer.get_token()
137-
if tok == 'define':
138-
name = lexer.get_token()
139-
expr = ''
94+
def parse_c_comments(lexer, tok, ntok):
95+
if tok != '/' or ntok != '*':
96+
return False
97+
quotes = lexer.quotes
98+
lexer.quotes = ''
14099
while True:
141-
142100
tok = lexer.get_token()
143101
ntok = lexer.get_token()
144-
145-
if parse_c_comments(lexer, tok, ntok):
146-
continue
147-
if parse_cpp_comments(lexer, tok, ntok):
148-
continue
149-
lexer.push_token(ntok)
150-
151-
if not tok or tok == '':
102+
if tok == '*' and ntok == '/':
103+
lexer.quotes = quotes
152104
break
105+
else:
106+
lexer.push_token(ntok)
107+
return True
108+
109+
def parse_cpp_comments(lexer, tok, ntok):
110+
if tok != '/' or ntok != '/':
111+
return False
112+
quotes = lexer.quotes
113+
lexer.quotes = ''
114+
while True:
115+
tok = lexer.get_token()
153116
if tok == '\n':
117+
lexer.quotes = quotes
154118
lexer.push_token(tok)
155119
break
120+
return True
156121

157-
if tok in out:
158-
tok = str(out[tok])
159-
expr = expr + tok
122+
while True:
123+
tok = lexer.get_token()
124+
if not tok or tok == '':
125+
break
126+
ntok = lexer.get_token()
160127

161-
try:
162-
val = eval_expr(expr)
163-
out[name] = val
164-
except (SyntaxError, TypeError):
165-
pass
166-
elif tok == 'include':
128+
if parse_c_comments(lexer, tok, ntok):
129+
continue
130+
if parse_cpp_comments(lexer, tok, ntok):
131+
continue
132+
133+
if tok != '\n' or ntok != '#':
134+
lexer.push_token(ntok)
135+
continue
167136

168137
tok = lexer.get_token()
169-
if tok == '<':
170-
name = ''
138+
if tok == 'define':
139+
name = lexer.get_token()
140+
expr = ''
171141
while True:
142+
172143
tok = lexer.get_token()
173-
if tok == '>':
144+
ntok = lexer.get_token()
145+
146+
if parse_c_comments(lexer, tok, ntok):
147+
continue
148+
if parse_cpp_comments(lexer, tok, ntok):
149+
continue
150+
lexer.push_token(ntok)
151+
152+
if not tok or tok == '':
153+
break
154+
if tok == '\n':
155+
lexer.push_token(tok)
174156
break
175-
name = name + tok
157+
158+
if tok in out:
159+
tok = str(out[tok])
160+
expr = expr + tok
161+
162+
try:
163+
val = eval_expr(expr)
164+
out[name] = val
165+
except (SyntaxError, TypeError):
166+
pass
167+
elif tok == 'include':
168+
169+
tok = lexer.get_token()
170+
if tok == '<':
171+
name = ''
172+
while True:
173+
tok = lexer.get_token()
174+
if tok == '>':
175+
break
176+
name = name + tok
177+
else:
178+
name = tok
179+
fname = os.path.normpath(os.path.abspath(os.path.join(base, name)))
180+
if os.path.isfile(fname) and not fname in parsed:
181+
parsed.add(fname)
182+
lexer.push_source(open(fname))
176183
else:
177-
name = tok
178-
fname = os.path.normpath(os.path.abspath(os.path.join(base, name)))
179-
if os.path.isfile(fname) and not fname in parsed:
180-
parsed.add(fname)
181-
lexer.push_source(open(fname))
182-
else:
183-
lexer.push_token(tok)
184+
lexer.push_token(tok)
184185

185186

186-
return out
187+
return out
187188

188189

189190
if __name__ == '__main__':

scc/device_monitor.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,8 @@ def _find_bt_address(syspath: str) -> str | None:
245245
"""Recursivelly searchs for "input*" subdirectories until "uniq" file is found. Then, returns address from that file."""
246246
uniq = os.path.join(syspath, "uniq")
247247
if os.path.exists(uniq):
248-
return open(uniq, "r").read().strip()
248+
with open(uniq, "r") as file:
249+
return file.read().strip()
249250
for name in os.listdir(syspath):
250251
if name.startswith("input"):
251252
path = os.path.join(syspath, name)

scc/foreign/vdf.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -581,7 +581,8 @@ def load(self, filename):
581581
582582
May raise ValueError.
583583
"""
584-
data = parse_vdf(open(filename, "r"))
584+
with open(filename, "r") as file:
585+
data = parse_vdf(file)
585586
self.load_data(data)
586587

587588

scc/gui/app.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -296,11 +296,13 @@ def check(self):
296296
# TODO: Maybe not best place to do this
297297
try:
298298
# Dynamic modules
299-
rawlist = open("/proc/modules", "r").read().split("\n")
299+
with open("/proc/modules", "r") as file:
300+
rawlist = file.read().split("\n")
300301
kernel_mods = [ line.split(" ")[0] for line in rawlist ]
301302
# Built-in modules
302303
release = platform.uname()[2]
303-
rawlist = open("/lib/modules/%s/modules.builtin" % release, "r").read().split("\n")
304+
with open("/lib/modules/%s/modules.builtin" % release, "r") as file:
305+
rawlist = file.read().split("\n")
304306
kernel_mods += [ os.path.split(x)[-1].split(".")[0] for x in rawlist ]
305307
except Exception:
306308
# Maybe running on BSD or Windows...

scc/gui/creg/dialog.py

Lines changed: 57 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -131,62 +131,63 @@ def load_sdl_mappings(self):
131131
log.exception(e)
132132
return False
133133

134-
for line in db.readlines():
135-
if line.startswith(weird_id):
136-
log.info("Loading mappings for '%s' from gamecontrollerdb", weird_id)
137-
log.debug("Buttons: %s", buttons)
138-
log.debug("Axes: %s", axes)
139-
for token in line.strip().split(","):
140-
if ":" in token:
141-
k, v = token.split(":", 1)
142-
k = SDL_TO_SCC_NAMES.get(k, k)
143-
if v.startswith("b") and hasattr(SCButtons, k.upper()):
144-
try:
145-
keycode = buttons[int(v.strip("b"))]
146-
except IndexError:
147-
log.warning("Skipping unknown gamecontrollerdb button->button mapping: '%s'", v)
148-
continue
149-
button = getattr(SCButtons, k.upper())
150-
self._mappings[keycode] = button
151-
elif v.startswith("b") and k in SDL_AXES:
152-
try:
153-
keycode = buttons[int(v.strip("b"))]
154-
except IndexError:
155-
log.warning("Skipping unknown gamecontrollerdb button->axis mapping: '%s'", v)
156-
continue
157-
log.info("Adding button -> axis mapping for %s", k)
158-
self._mappings[keycode] = self._axis_data[SDL_AXES.index(k)]
159-
self._mappings[keycode].min = STICK_PAD_MIN
160-
self._mappings[keycode].max = STICK_PAD_MAX
161-
elif v.startswith("h") and 16 in axes and 17 in axes:
162-
# Special case for evdev hatswitch
163-
if v == "h0.1" and k == "dpup":
164-
self._mappings[16] = self._axis_data[SDL_AXES.index("dpadx")]
165-
self._mappings[17] = self._axis_data[SDL_AXES.index("dpady")]
166-
elif k in SDL_AXES:
167-
try:
168-
code = axes[int(v.strip("a"))]
169-
except IndexError:
170-
log.warning("Skipping unknown gamecontrollerdb axis: '%s'", v)
171-
continue
172-
self._mappings[code] = self._axis_data[SDL_AXES.index(k)]
173-
elif k in SDL_DPAD and v.startswith("b"):
174-
try:
175-
keycode = buttons[int(v.strip("b"))]
176-
except IndexError:
177-
log.warning("Skipping unknown gamecontrollerdb button->dpad mapping: %s", v)
178-
continue
179-
index, positive = SDL_DPAD[k]
180-
data = DPadEmuData(self._axis_data[index], positive)
181-
self._mappings[keycode] = data
182-
elif k == "platform":
183-
# Not interesting
184-
pass
185-
else:
186-
log.warning("Skipping unknown gamecontrollerdb mapping %s:%s", k, v)
187-
return True
188-
else:
189-
log.debug("Mappings for '%s' not found in gamecontrollerdb", weird_id)
134+
with db:
135+
for line in db.readlines():
136+
if line.startswith(weird_id):
137+
log.info("Loading mappings for '%s' from gamecontrollerdb", weird_id)
138+
log.debug("Buttons: %s", buttons)
139+
log.debug("Axes: %s", axes)
140+
for token in line.strip().split(","):
141+
if ":" in token:
142+
k, v = token.split(":", 1)
143+
k = SDL_TO_SCC_NAMES.get(k, k)
144+
if v.startswith("b") and hasattr(SCButtons, k.upper()):
145+
try:
146+
keycode = buttons[int(v.strip("b"))]
147+
except IndexError:
148+
log.warning("Skipping unknown gamecontrollerdb button->button mapping: '%s'", v)
149+
continue
150+
button = getattr(SCButtons, k.upper())
151+
self._mappings[keycode] = button
152+
elif v.startswith("b") and k in SDL_AXES:
153+
try:
154+
keycode = buttons[int(v.strip("b"))]
155+
except IndexError:
156+
log.warning("Skipping unknown gamecontrollerdb button->axis mapping: '%s'", v)
157+
continue
158+
log.info("Adding button -> axis mapping for %s", k)
159+
self._mappings[keycode] = self._axis_data[SDL_AXES.index(k)]
160+
self._mappings[keycode].min = STICK_PAD_MIN
161+
self._mappings[keycode].max = STICK_PAD_MAX
162+
elif v.startswith("h") and 16 in axes and 17 in axes:
163+
# Special case for evdev hatswitch
164+
if v == "h0.1" and k == "dpup":
165+
self._mappings[16] = self._axis_data[SDL_AXES.index("dpadx")]
166+
self._mappings[17] = self._axis_data[SDL_AXES.index("dpady")]
167+
elif k in SDL_AXES:
168+
try:
169+
code = axes[int(v.strip("a"))]
170+
except IndexError:
171+
log.warning("Skipping unknown gamecontrollerdb axis: '%s'", v)
172+
continue
173+
self._mappings[code] = self._axis_data[SDL_AXES.index(k)]
174+
elif k in SDL_DPAD and v.startswith("b"):
175+
try:
176+
keycode = buttons[int(v.strip("b"))]
177+
except IndexError:
178+
log.warning("Skipping unknown gamecontrollerdb button->dpad mapping: %s", v)
179+
continue
180+
index, positive = SDL_DPAD[k]
181+
data = DPadEmuData(self._axis_data[index], positive)
182+
self._mappings[keycode] = data
183+
elif k == "platform":
184+
# Not interesting
185+
pass
186+
else:
187+
log.warning("Skipping unknown gamecontrollerdb mapping %s:%s", k, v)
188+
return True
189+
else:
190+
log.debug("Mappings for '%s' not found in gamecontrollerdb", weird_id)
190191

191192
return False
192193

scc/gui/global_settings.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -669,7 +669,8 @@ def on_cbOSDStyle_changed(self, cb):
669669
color_keys = self.app.config['osk_colors'].keys() + self.app.config['osd_colors'].keys()
670670
osd_style = cb.get_model().get_value(cb.get_active_iter(), 0)
671671
css_file = os.path.join(get_share_path(), "osd-styles", osd_style)
672-
first_line = open(css_file, "r").read().split("\n")[0]
672+
with open(css_file, "r") as file:
673+
first_line = file.read().split("\n")[0]
673674
used_colors = None # None means "all"
674675
if "Used colors:" in first_line:
675676
used_colors = set(first_line.split(":", 1)[1].strip(" */").split(" "))

scc/gui/icon_chooser.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -176,10 +176,11 @@ def find_license(path, name):
176176
licensefile = os.path.join(path, "LICENSES")
177177
if not os.path.exists(licensefile):
178178
return None
179-
for line in open(licensefile, "r").readlines():
180-
if line.startswith(name):
181-
if "-" in line:
182-
return line.split("-")[-1].strip("\t\r\n ")
179+
with open(licensefile, "r") as file:
180+
for line in file.readlines():
181+
if line.startswith(name):
182+
if "-" in line:
183+
return line.split("-")[-1].strip("\t\r\n ")
183184
return None
184185

185186

0 commit comments

Comments
 (0)