How to capture function output? #3180
-
Beta Was this translation helpful? Give feedback.
      
      
          Answered by
          
            TomJGooding
          
      
      
        Aug 28, 2023 
      
    
    Replies: 1 comment 12 replies
-
| Since your function "will execute for a while", for starters I'd recommend having a look at the Workers guide in the docs. I've seen a few questions like this about redirecting stdout in Textual, so I think this really needs an 'official' answer from a maintainer. Perhaps it might even be worth adding to the FAQ at some point? After some quick research, here's my attempt at this which uses contextlib.redirect_stdout. I do not recommend using this, as I have no idea if it is thread safe! import contextlib
from time import sleep
from textual import work
from textual.app import App, ComposeResult
from textual.widgets import Footer, RichLog
def long_blocking_process() -> None:
    print("Connecting")
    sleep(3)
    print("Searching")
    sleep(3)
    print("Creating")
class OutputLog:
    def __init__(self, log: RichLog) -> None:
        self.log = log
    def write(self, text: str) -> None:
        if text.strip():
            app = self.log.app
            app.call_from_thread(self.log.write, text)
    def flush(self) -> None:
        pass
class WorkerWithRedirectStdoutApp(App):
    BINDINGS = [
        ("space", "run_long_blocking_process", "Run long blocking process"),
    ]
    def compose(self) -> ComposeResult:
        yield RichLog()
        yield Footer()
    @work(exclusive=True, thread=True)
    def action_run_long_blocking_process(self) -> None:
        log = self.query_one(RichLog)
        with contextlib.redirect_stdout(OutputLog(log)):  # type: ignore[type-var]
            long_blocking_process()
if __name__ == "__main__":
    app = WorkerWithRedirectStdoutApp()
    app.run() | 
Beta Was this translation helpful? Give feedback.
                  
                    12 replies
                  
                
            
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
Thanks Will, yup that works better. Here's the full example with that tweak just for future reference: