main.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python3
  2. import asyncio
  3. import os.path
  4. import platform
  5. import shlex
  6. from nicegui import 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. ui.button('python3 hello.py', on_click=lambda: run_command('python3 hello.py')).props('no-caps')
  28. ui.button('python3 slow.py', on_click=lambda: run_command('python3 slow.py')).props('no-caps')
  29. with ui.row().classes('items-center'):
  30. ui.button('python3 hello.py "<message>"', on_click=lambda: run_command(f'python3 hello.py "{message.value}"')) \
  31. .props('no-caps')
  32. message = ui.input('message', value='NiceGUI')
  33. # NOTE: On Windows reload must be disabled to make asyncio.create_subprocess_exec work (see https://github.com/zauberzeug/nicegui/issues/486)
  34. ui.run(reload=platform.system() != 'Windows')