Skip to content

Instantly share code, notes, and snippets.

@jcheng5
Last active February 2, 2024 16:24
Show Gist options
  • Save jcheng5/d16a0280f87a2b1bde4511a318eb0571 to your computer and use it in GitHub Desktop.
Save jcheng5/d16a0280f87a2b1bde4511a318eb0571 to your computer and use it in GitHub Desktop.
Shiny for Python module for console you can write to
from shiny import App, reactive, render, ui, module
from shiny.session import Session
from contextlib import redirect_stdout, redirect_stderr
import asyncio
from shiny_console import Console, console_ui, console_server
# == Example usage =======================================
app_ui = ui.page_fluid(
ui.input_task_button("go", "Go"),
console_ui("one"),
class_="p-3"
)
def server(input, output, session):
console = console_server("one")
@reactive.effect
@reactive.event(input.go)
async def _():
console.clear()
with redirect_stdout(console):
with redirect_stderr(console):
await asyncio.sleep(1)
print("one")
await asyncio.sleep(1)
print("two")
app = App(app_ui, server)
from shiny import App, reactive, render, ui, module
from shiny.session import Session
class Console:
def __init__(self, selector: str, session: Session):
self._selector = selector
self._session = session
def write(self, s: str):
ui.insert_ui(
s,
f"{self._selector} > .out",
"beforeEnd",
immediate=True,
session=self._session,
)
def clear(self):
ui.remove_ui(
f"{self._selector} > .out",
immediate=True,
session=self._session,
)
ui.insert_ui(
ui.pre(class_="out"),
self._selector,
"beforeEnd",
immediate=True,
session=self._session,
)
def flush(self):
pass
@module.ui
def console_ui():
return ui.div(
ui.pre(class_="out"),
id=module.resolve_id("console"),
)
@module.server
def console_server(input, output, session):
return Console(f"#{session.ns('console')}", session)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment