main.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/env python3
  2. import asyncio
  3. import os.path
  4. import shlex
  5. from nicegui import background_tasks, ui
  6. async def run_command(command: str) -> None:
  7. '''Run a command in the background and display the output in the pre-created dialog.'''
  8. dialog.open()
  9. result.content = ''
  10. process = await asyncio.create_subprocess_exec(
  11. *shlex.split(command),
  12. stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
  13. cwd=os.path.dirname(os.path.abspath(__file__))
  14. )
  15. # NOTE we need to read the output in chunks, otherwise the process will block
  16. output = ''
  17. while True:
  18. new = await process.stdout.read(4096)
  19. if not new:
  20. break
  21. output += new.decode()
  22. # NOTE the content of the markdown element is replaced every time we have new output
  23. result.content = f'```\n{output}\n```'
  24. with ui.dialog() as dialog, ui.card():
  25. result = ui.markdown()
  26. commands = ['python3 hello.py', 'python3 hello.py NiceGUI', 'python3 slow.py']
  27. with ui.row():
  28. for command in commands:
  29. ui.button(command, on_click=lambda _, c=command: background_tasks.create(run_command(c))).props('no-caps')
  30. ui.run()