[Lldb-commits] [lldb] [lldb/Interpreter] Propagate `script` output back to command return object (PR #109440)

Pavel Labath via lldb-commits lldb-commits at lists.llvm.org
Mon Sep 23 00:27:37 PDT 2024


================
@@ -116,19 +118,50 @@ def run_python_interpreter(local_dict):
             print("Script exited with code %s" % e.code)
 
 
+class LLDBInteractiveConsole(code.InteractiveConsole):
+    def __init__(self, locals=None):
+        super().__init__(locals)
+        self.result_output = None
+
+    ### Implementation detail:
+    ### https://docs.python.org/3/library/code.html#code.InteractiveInterpreter.runsource
+    def runsource(self, source, filename="<input>", symbol="single"):
+        # Redirect stdout to capture print statements
+        old_stdout = sys.stdout
+        sys.stdout = result_output = StringIO()
----------------
labath wrote:

Apparently, there's even a [standard utility](https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout) to do this, but it comes with a big warning (which I fully agree with):

```
Note that the global side effect on [sys.stdout](https://docs.python.org/3/library/sys.html#sys.stdout) means that this context manager is not suitable for use in library code and most threaded applications.
```

We tick both of those boxes. Is this redirection really necessary? Does anything prevent two instances of this function from running in parallel (e.g. on two debugger objects). If not, we're just setting ourself for a nasty race where the stdout just suddenly goes dead (because it's been permanently redirected to StringIO).  (Note that even if we can prevent races between in our own code, we can't prevent racing with anyone else attempting to do the same thing, nor we can stop inadvertently  capturing the output of other threads).

Capturing the result of the command makes sense to me, but capturing stdout, seems like its going too far. Maybe we could provide the StringIO object to the executed code as some sort of an argument, so that if the user really wants print there it can do something like `print(..., file=cmd_output)` ?

https://github.com/llvm/llvm-project/pull/109440


More information about the lldb-commits mailing list