Skip to content

Commit 2b20964

Browse files
authored
grass.gunittest: Solve ResourceWarning in gs.parser() coming from sys.stdout (OSGeo#6196)
The note at the end of [`sys.stdout`'s docs](https://docs.python.org/3/library/sys.html#sys.stdout) mentions that writing binary data to the standard streams should use the underlying binary buffer object. However, that file might be replaced by a file-like object that doesn't support the buffer attribute. So, inspired by [the code example for `sys.displayhook`](https://docs.python.org/3.13/library/sys.html#sys.displayhook), use the binary buffer object if available or simply write the encoded text otherwise. This solves multiple ResourceWarnings found in tests that could be traced back to this when enabling python tracemalloc as written in the warning messages. One of the ways is to set the env var `PYTHONTRACEMALLOC` to the number of frames to keep. So, `export PYTHONTRACEMALLOC=15` is enough.
1 parent edc87a4 commit 2b20964

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

python/grass/script/core.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1095,8 +1095,11 @@ def parser() -> tuple[dict[str, str], dict[str, bool]]:
10951095
s = p.communicate()[0]
10961096
lines = s.split(b"\0")
10971097
if not lines or lines[0] != b"@ARGS_PARSED@":
1098-
stdout = os.fdopen(sys.stdout.fileno(), "wb")
1099-
stdout.write(s)
1098+
if hasattr(sys.stdout, "buffer"):
1099+
sys.stdout.buffer.write(s)
1100+
else:
1101+
text = s.decode(sys.stdout.encoding, "strict")
1102+
sys.stdout.write(text)
11001103
sys.exit(p.returncode)
11011104
return _parse_opts(lines[1:])
11021105

0 commit comments

Comments
 (0)