os.misc.cmd_exec(): Fix echo_cmd=False

cmd_exec() sometimes returned the command in the output albeit
echo_cmd=False was specified, notably if the command contained a
newline.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2022-12-07 09:53:43 +01:00
commit 7d709ecc58

View file

@ -24,12 +24,13 @@ def consume_readbuffer(buf, carry, cmd, log_act=None, caller=None):
caller = get_caller_pos(2)
for line in lines:
slog(log_act, line, caller=caller)
stripped_cmd = cmd.strip() if isinstance(cmd, str) else None
for line in lines:
if line.find(cmd) != -1:
slog(DEBUG, "ignoring echoed command >{}<".format(cmd))
else:
r.append(line)
if not buf.endswith(('\n', '\r')):
if stripped_cmd is not None and stripped_cmd == line:
slog(DEBUG, "ignoring echoed command >{}<".format(stripped_cmd))
continue
r.append(line)
if len(r) and not buf.endswith(('\n', '\r')):
carry = r.pop(-1)
return r, carry
@ -43,22 +44,21 @@ async def cmd_exec(conn, cmd, act_timeout=0.1, total_timeout=None, newlines=Fals
if isinstance(cmd, str) and not cmd.endswith('\n'):
cmd += '\n'
slog_m(DEBUG, 'connection {}, timemout {}/{}: writing command "{}"'.format(
conn, act_timeout, total_timeout, cmd), only_printable=True)
conn, act_timeout, total_timeout, cmd.strip()), only_printable=True)
await conn.write(cmd)
end = datetime.now() + timedelta(seconds=total_timeout) if total_timeout else None
carry = ''
while True:
rest = min((end - datetime.now()).total_seconds(), act_timeout) if end else act_timeout
rest = min((end - datetime.now()).total_seconds(), act_timeout) if end is not None else act_timeout
if rest >= 0:
slog(DEBUG, 'connection {}: starting read() with timeout {}'.format(conn, rest))
buf = await conn.read(act_timeout=rest)
slog_m(DEBUG, 'connection {}: read response "{}"'.format(conn, buf))
if buf is not None and end and len(buf) == 0 and datetime.now() < end:
raise Exception("connection {} reset while reading command response".format(conn))
ret, carry = consume_readbuffer(buf, carry, cmd, log_act=log_act, caller=caller)
ret, carry = consume_readbuffer(buf, carry, None if echo_cmd else cmd, log_act=log_act, caller=caller)
r.extend(ret)
if rest < 0 or not buf:
if not echo_cmd and cmd in r:
r.remove(cmd)
d = os.getenv("JW_DEVTEST_RESPONSE_DIR")
if d is not None:
path = d + '/' + re.sub('[^a-zA-Z0-9]+', '_', cmd)