main.py 1.4 KB

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