瀏覽代碼

explanations for the script executor example

Rodja Trappe 2 年之前
父節點
當前提交
fbc878aa6c
共有 1 個文件被更改,包括 8 次插入4 次删除
  1. 8 4
      examples/script_executor/main.py

+ 8 - 4
examples/script_executor/main.py

@@ -7,19 +7,23 @@ from nicegui import background_tasks, ui
 
 
 
 
 async def run_command(command: str) -> None:
 async def run_command(command: str) -> None:
+    '''Run a command in the background and display the output in the pre-created dialog.'''
     dialog.open()
     dialog.open()
     result.content = ''
     result.content = ''
     process = await asyncio.create_subprocess_exec(
     process = await asyncio.create_subprocess_exec(
         *shlex.split(command),
         *shlex.split(command),
         stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
         stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
-        cwd=os.path.dirname(os.path.abspath(__file__)))
-    content = ''
+        cwd=os.path.dirname(os.path.abspath(__file__))
+    )
+    # NOTE we need to read the output in chunks, otherwise the process will block
+    output = ''
     while True:
     while True:
         new = await process.stdout.read(4096)
         new = await process.stdout.read(4096)
         if not new:
         if not new:
             break
             break
-        content += new.decode()
-        result.content = f'```\n{content}\n```'
+        output += new.decode()
+        # NOTE the content of the markdown element is replaced every time we have new output
+        result.content = f'```\n{output}\n```'
 
 
 with ui.dialog() as dialog, ui.card():
 with ui.dialog() as dialog, ui.card():
     result = ui.markdown()
     result = ui.markdown()