Skip to content

Commit 5733f2a

Browse files
felipegetuliocodeskyblue
authored andcommitted
Fix close connection when using shell v2
- Added try-finally blocks to handle socket connection - This fix is due to resolve the following warning: ResourceWarning: unclosed <socket.socket fd=54, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 41156), raddr=('127.0.0.1', 5037)> 23:02:01 result = self._shell_v2(cmdargs, timeout) -
1 parent 664b89f commit 5733f2a

1 file changed

Lines changed: 34 additions & 31 deletions

File tree

adbutils/_device_base.py

Lines changed: 34 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -284,37 +284,40 @@ def _shell_v1(self, cmdargs: str, timeout: Optional[float] = _DEFAULT_SOCKET_TIM
284284

285285
def _shell_v2(self, cmdargs: str, timeout: Optional[float] = _DEFAULT_SOCKET_TIMEOUT) -> ShellReturnRaw:
286286
c = self.open_transport(timeout=timeout)
287-
c.send_command(f"shell,v2:{cmdargs}")
288-
c.check_okay()
289-
stdout_buffer = io.BytesIO()
290-
stderr_buffer = io.BytesIO()
291-
output_buffer = io.BytesIO()
292-
exit_code = 255
293-
294-
while True:
295-
header = c.read_exact(5)
296-
msg_id = header[0]
297-
length = int.from_bytes(header[1:5], byteorder="little")
298-
if length == 0:
299-
continue
300-
301-
data = c.read_exact(length)
302-
if msg_id == 1:
303-
stdout_buffer.write(data)
304-
output_buffer.write(data)
305-
elif msg_id == 2:
306-
stderr_buffer.write(data)
307-
output_buffer.write(data)
308-
elif msg_id == 3:
309-
exit_code = data[0]
310-
break
311-
return ShellReturnRaw(
312-
command=cmdargs,
313-
returncode=exit_code,
314-
output=output_buffer.getvalue(),
315-
stderr=stderr_buffer.getvalue(),
316-
stdout=stdout_buffer.getvalue(),
317-
)
287+
try:
288+
c.send_command(f"shell,v2:{cmdargs}")
289+
c.check_okay()
290+
stdout_buffer = io.BytesIO()
291+
stderr_buffer = io.BytesIO()
292+
output_buffer = io.BytesIO()
293+
exit_code = 255
294+
295+
while True:
296+
header = c.read_exact(5)
297+
msg_id = header[0]
298+
length = int.from_bytes(header[1:5], byteorder="little")
299+
if length == 0:
300+
continue
301+
302+
data = c.read_exact(length)
303+
if msg_id == 1:
304+
stdout_buffer.write(data)
305+
output_buffer.write(data)
306+
elif msg_id == 2:
307+
stderr_buffer.write(data)
308+
output_buffer.write(data)
309+
elif msg_id == 3:
310+
exit_code = data[0]
311+
break
312+
return ShellReturnRaw(
313+
command=cmdargs,
314+
returncode=exit_code,
315+
output=output_buffer.getvalue(),
316+
stderr=stderr_buffer.getvalue(),
317+
stdout=stdout_buffer.getvalue(),
318+
)
319+
finally:
320+
c.close()
318321

319322
def forward(self, local: str, remote: str, norebind: bool = False):
320323
cmd = "forward"

0 commit comments

Comments
 (0)