[docs]defexecute_python_code(code:str,timeout:float=300,**kwargs:Any,)->ServiceResponse:"""Execute the given python code in a temp file and capture the return code, standard output and error. Note you must `print` the output to get the result, and the tmp file will be removed right after the execution. Args: code (`str`): The Python code to be executed. timeout (`float`, defaults to `300`): The maximum time (in seconds) allowed for the code to run. Returns: `ServiceResponse`: The status field indicates whether the code execution was successful. The content field contains the return code, standard output, and standard error of the executed code. """# noqawithtempfile.TemporaryDirectory()astemp_dir:temp_file=os.path.join(temp_dir,f"tmp_{shortuuid.uuid()}.py")withopen(temp_file,"w",encoding="utf-8")asf:f.write(code)try:res=subprocess.run([sys.executable,temp_file],text=True,capture_output=True,timeout=timeout,check=False,)returnServiceResponse(status=ServiceExecStatus.SUCCESS,content=(f"<returncode>{res.returncode}</returncode>\n"f"<stdout>{res.stdout}</stdout>\n"f"<stderr>{res.stderr}</stderr>"),)exceptsubprocess.TimeoutExpiredase:stdout=e.stdout.decode("utf-8")ife.stdoutelse""returnServiceResponse(status=ServiceExecStatus.ERROR,content=("<returncode>-1</returncode>\n"f"<stdout>{stdout}</stdout>\n""<stderr>Error: Python code execution timeout after "f"{timeout} seconds. Consider increasing the timeout "f"value or adjusting your code<stderr>"),)