Skip to content

Commit

Permalink
✨ feat: added a rolling buffer for the func execute_command
Browse files Browse the repository at this point in the history
  • Loading branch information
huangyz0918 committed Oct 21, 2024
1 parent e57ac0a commit d7d1391
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions mle/function/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,38 @@
"""

import subprocess
from collections import deque


def execute_command(command: str):
def execute_command(command: str, max_lines: int = 30):
"""
Run multiple commands in the shell and return the outputs, errors, and exit statuses.
Run a command in the shell and return the outputs, errors, and exit status,
limiting the output to a specified number of most recent lines.
Args:
command: the list of input commands to run.
command (str): The input command to run.
max_lines (int): Maximum number of output lines to keep. Defaults to 100.
Return: a string of the output, error (if any), and exit status for the command.
Return: A string of the exit status and the limited output (most recent lines).
"""
try:
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
output = ''
output_buffer = deque(maxlen=max_lines)

while True:
line = process.stdout.readline()
if not line and process.poll() is not None:
break
output += line
output_buffer.append(line.rstrip())
print(line, end='')

exit_code = process.wait()
return f"Exit code: {exit_code} \nOutput: \n{output}"

limited_output = "\n".join(output_buffer)
if len(output_buffer) == max_lines:
return f"Exit code: {exit_code}\nOutput (last {max_lines} lines):\n{limited_output}"
else:
return f"Exit code: {exit_code}\nOutput:\n{limited_output}"

except Exception as e:
return f"Error running command: {str(e)}"

0 comments on commit d7d1391

Please sign in to comment.