Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

fix: Subprocess interpreter don't have output (#1590)

Wendong-Fanb87dc6ed9373
diff --git a/camel/interpreters/subprocess_interpreter.py b/camel/interpreters/subprocess_interpreter.py
index b5ba04d31..82951755a 100644
--- a/camel/interpreters/subprocess_interpreter.py
+++ b/camel/interpreters/subprocess_interpreter.py
@@ -98,15 +98,70 @@ class SubprocessInterpreter(BaseInterpreter):
if not file.is_file():
raise RuntimeError(f"{file} is not a file.")
code_type = self._check_code_type(code_type)
- cmd = shlex.split(
- self._CODE_EXECUTE_CMD_MAPPING[code_type].format(
- file_name=str(file)
+ if code_type == "python":
+ # For Python code, use ast to analyze and modify the code
+ import ast
+
+ import astor
+
+ with open(file, 'r') as f:
+ source = f.read()
+
+ # Parse the source code
+ try:
+ tree = ast.parse(source)
+ # Get the last node
+ if tree.body:
+ last_node = tree.body[-1]
+ # If it's an expression, wrap it in a print
+ if isinstance(last_node, ast.Expr):
+ tree.body[-1] = ast.Expr(
+ value=ast.Call(
+ func=ast.Name(id='print', ctx=ast.Load()),
+ args=[
+ ast.Call(
+ func=ast.Name(
+ id='repr', ctx=ast.Load()
+ ),
+ args=[last_node.value],
+ keywords=[],
+ )
+ ],
+ keywords=[],
+ )
+ )
+ # Fix missing source locations
+ ast.fix_missing_locations(tree)
+ # Convert back to source
+ modified_source = astor.to_source(tree)
+ # Create a temporary file with the modified source
+ temp_file = self._create_temp_file(modified_source, "py")
+ cmd = shlex.split(f"python {temp_file!s}")
+ except SyntaxError:
+ # If parsing fails, run the original file
+ cmd = shlex.split(
+ self._CODE_EXECUTE_CMD_MAPPING[code_type].format(
+ file_name=str(file)
+ )
+ )
+ else:
+ # For non-Python code, use standard execution
+ cmd = shlex.split(
+ self._CODE_EXECUTE_CMD_MAPPING[code_type].format(
+ file_name=str(file)
+ )
)
- )
+
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
stdout, stderr = proc.communicate()
+ return_code = proc.returncode
+
+ # Clean up temporary file if it was created
+ if code_type == "python" and 'temp_file' in locals():
+ temp_file.unlink()
+
if self.print_stdout and stdout:
print("======stdout======")
print(Fore.GREEN + stdout + Fore.RESET)
@@ -115,8 +170,19 @@ class SubprocessInterpreter(BaseInterpreter):
print("======stderr======")
print(Fore.RED + stderr + Fore.RESET)
print("==================")
- exec_result = f"{stdout}"
- exec_result += f"(stderr: {stderr})" if stderr else ""
+
+ # Build the execution result
+ exec_result = ""
+ if stdout:
+ exec_result += stdout
+ if stderr:
+ exec_result += f"(stderr: {stderr})"
+ if return_code != 0:
+ error_msg = f"(Execution failed with return code {return_code})"
+ if not stderr:
+ exec_result += error_msg
+ elif error_msg not in stderr:
+ exec_result += error_msg
return exec_result
def run(
diff --git a/pyproject.toml b/pyproject.toml
index 226c547aa..5d6d679fe 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -538,5 +538,6 @@ module = [
"pandasai",
"sklearn.metrics.pairwise",
"sympy",
+ "astor",
]
ignore_missing_imports = true
\ No newline at end of file
diff --git a/test/prompts/test_prompt_base.py b/test/prompts/test_prompt_base.py
index c7a249a38..688e08c9d 100644
--- a/test/prompts/test_prompt_base.py
+++ b/test/prompts/test_prompt_base.py
@@ -140,7 +140,7 @@ def test_code_prompt_execute(monkeypatch):
"a = 1\nprint('Hello, World!')", code_type="python"
)
result = code_prompt.execute()
- assert result == "Hello, World!\n"
+ assert result == "Hello, World!\nNone\n"
def test_code_prompt_execute_error(monkeypatch):