lollms-webui/utilities/execution_engines/shell_execution_engine.py

81 lines
2.4 KiB
Python
Raw Normal View History

"""
project: lollms_webui
file: shell_execution_engine.py
author: ParisNeo
description:
This is a utility for executing python code
"""
2024-12-19 12:48:57 +00:00
import json
2024-12-19 12:48:57 +00:00
import subprocess
import time
from ascii_colors import get_trace_exception, trace_exception
2024-02-28 00:06:59 +00:00
from lollms.client_session import Client
2024-12-19 12:48:57 +00:00
from lollms_webui import LOLLMSWebUI
lollmsElfServer: LOLLMSWebUI = LOLLMSWebUI.get_instance()
2024-12-19 12:48:57 +00:00
def execute_bash(code, client: Client, message_id, build_file=False):
def spawn_process(code):
"""Executes Python code and returns the output as JSON."""
# Start the timer.
start_time = time.time()
# Create a temporary file.
2024-02-28 00:06:59 +00:00
root_folder = client.discussion.discussion_folder
2024-12-19 12:48:57 +00:00
root_folder.mkdir(parents=True, exist_ok=True)
try:
# Execute the Python code in a temporary file.
2024-12-19 12:48:57 +00:00
process = subprocess.Popen(
code,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
2024-12-19 12:48:57 +00:00
cwd=client.discussion.discussion_folder,
)
# Get the output and error from the process.
output, error = process.communicate()
except Exception as ex:
# Stop the timer.
execution_time = time.time() - start_time
error_message = f"Error executing Python code: {ex}"
2024-12-19 12:48:57 +00:00
error_json = {
"output": "<div class='text-red-500'>"
+ str(ex)
+ "\n"
+ get_trace_exception(ex)
+ "</div>",
"execution_time": execution_time,
}
2024-01-07 23:22:23 +00:00
return error_json
# Stop the timer.
execution_time = time.time() - start_time
# Check if the process was successful.
if process.returncode != 0:
# The child process threw an exception.
2024-12-19 12:48:57 +00:00
error_message = (
f"Error executing Python code: {error.decode('utf8','ignore')}"
)
error_json = {
"output": "<div class='text-red-500'>" + error_message + "</div>",
"execution_time": execution_time,
}
2024-01-07 23:22:23 +00:00
return error_json
# The child process was successful.
2024-12-19 12:48:57 +00:00
output_json = {
"output": output.decode("utf8"),
"execution_time": execution_time,
}
2024-01-07 23:22:23 +00:00
return output_json
2024-12-19 12:48:57 +00:00
2024-03-08 14:00:00 +00:00
return spawn_process(code)