Files
ai-agent-gemini/functions/run_python_file.py
T

39 lines
1.5 KiB
Python

import os
import subprocess
def run_python_file(working_directory, file_path, args=None):
try:
abs_path = os.path.abspath(working_directory)
new_file_path = os.path.normpath(os.path.join(abs_path, file_path))
valid_target_file = os.path.commonpath([abs_path, new_file_path]) == abs_path
if not valid_target_file:
return f'Error: Cannot execute "{file_path}" as it is outside the permitted working directory'
if not os.path.isfile(new_file_path):
return f'Error: "{file_path}" does not exist or is not a regular file'
if not file_path.endswith(".py"):
return f'Error: "{file_path}" is not a Python file'
command = ["python", new_file_path]
if args:
command.extend(args)
completed_process = subprocess.run(
command,
cwd=abs_path,
capture_output=True,
text=True,
timeout=30
)
output = []
if completed_process.returncode != 0:
output.append(f"Process exited with code {completed_process.returncode}")
if not completed_process.stdout and not completed_process.stderr:
output.append("No output produced")
if completed_process.stdout:
output.append(f"STDOUT: {completed_process.stdout}")
if completed_process.stderr:
output.append(f"STDERR: {completed_process.stderr}")
return "\n".join(output)
except Exception as e:
return f"Error: executing Python file: {e}"