Execute Python code and return the numeric output as a string.
(code: str)
| 46 | |
| 47 | |
| 48 | def execute_python_code(code: str) -> str: |
| 49 | """ |
| 50 | Execute Python code and return the numeric output as a string. |
| 51 | """ |
| 52 | # Remove any surrounding quotes and whitespace |
| 53 | code = code.strip().strip("'").strip('"') |
| 54 | |
| 55 | # Create a temporary file with the code |
| 56 | import tempfile |
| 57 | |
| 58 | with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=True) as tmp: |
| 59 | tmp.write(code) |
| 60 | tmp.flush() |
| 61 | |
| 62 | # Execute the temporary file using uv |
| 63 | result = execute(f"uv run {tmp.name} --ignore-warnings") |
| 64 | |
| 65 | # Try to parse the result as a number |
| 66 | try: |
| 67 | # Remove any extra whitespace or newlines |
| 68 | cleaned_result = result.strip() |
| 69 | # Convert to float and back to string to normalize format |
| 70 | return str(float(cleaned_result)) |
| 71 | except (ValueError, TypeError): |
| 72 | # If conversion fails, return the raw result |
| 73 | return result |
| 74 | |
| 75 | |
| 76 | def execute(code: str) -> str: |
no test coverage detected