main.py 1.7 KB

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