Execute Python code in FreeCAD context with enhanced safety and logging
(self, args: Dict[str, Any])
| 2194 | return f"Error activating workbench: {e}" |
| 2195 | |
| 2196 | def _execute_python(self, args: Dict[str, Any]) -> str: |
| 2197 | """Execute Python code in FreeCAD context with enhanced safety and logging""" |
| 2198 | import traceback |
| 2199 | import time |
| 2200 | |
| 2201 | try: |
| 2202 | code = args.get('code', '') |
| 2203 | timestamp = time.strftime("%Y-%m-%d %H:%M:%S") |
| 2204 | |
| 2205 | FreeCAD.Console.PrintMessage(f"[{timestamp}] EXEC START: {repr(code[:100])}...\n") |
| 2206 | |
| 2207 | # Enhanced pre-flight safety checks |
| 2208 | if 'newDocument' in code: |
| 2209 | FreeCAD.Console.PrintMessage("DETECTED: Document creation operation\n") |
| 2210 | try: |
| 2211 | # Comprehensive state check |
| 2212 | version = FreeCAD.Version() |
| 2213 | docs = FreeCAD.listDocuments() |
| 2214 | active = FreeCAD.ActiveDocument |
| 2215 | |
| 2216 | FreeCAD.Console.PrintMessage(f"Pre-flight: Version={version}, Docs={list(docs.keys())}, Active={active}\n") |
| 2217 | |
| 2218 | # Test memory allocation |
| 2219 | test_list = list(range(1000)) # Small memory test |
| 2220 | FreeCAD.Console.PrintMessage("Pre-flight: Memory test passed\n") |
| 2221 | |
| 2222 | except Exception as e: |
| 2223 | FreeCAD.Console.PrintError(f"Pre-flight FAILED: {e}\n") |
| 2224 | return f"FreeCAD not ready for document operations: {e}" |
| 2225 | |
| 2226 | # Create enhanced execution context |
| 2227 | exec_context = { |
| 2228 | 'FreeCAD': FreeCAD, |
| 2229 | 'FreeCADGui': FreeCADGui, |
| 2230 | 'doc': FreeCAD.ActiveDocument, |
| 2231 | 'print': lambda *args: FreeCAD.Console.PrintMessage('CODE: ' + ' '.join(str(arg) for arg in args) + '\n') |
| 2232 | } |
| 2233 | |
| 2234 | # Execute with detailed logging |
| 2235 | FreeCAD.Console.PrintMessage("EXEC: Starting code execution...\n") |
| 2236 | |
| 2237 | try: |
| 2238 | exec(code, exec_context) |
| 2239 | FreeCAD.Console.PrintMessage("EXEC: Code completed successfully\n") |
| 2240 | except Exception as exec_error: |
| 2241 | FreeCAD.Console.PrintError(f"EXEC: Code execution failed: {exec_error}\n") |
| 2242 | FreeCAD.Console.PrintError(f"EXEC: Traceback: {traceback.format_exc()}\n") |
| 2243 | raise exec_error |
| 2244 | |
| 2245 | # Return result if available |
| 2246 | if 'result' in exec_context: |
| 2247 | result = str(exec_context['result']) |
| 2248 | FreeCAD.Console.PrintMessage(f"EXEC: Result: {result}\n") |
| 2249 | return result |
| 2250 | else: |
| 2251 | FreeCAD.Console.PrintMessage("EXEC: No explicit result, returning success\n") |
| 2252 | return "Code executed successfully" |
| 2253 |
no outgoing calls
no test coverage detected