Search code examples
pythonpowershellterminalholovizholoviz-panel

Is it possible to exit the command window when Holoviz Panel application browser window is closed?


I am writing an application that uses Holoviz panel. After interaction with the application is completed, I close the browser window, but the server remains running in the terminal/command line window.

Is it possible to automatically close the terminal/command line window if the browser tab displaying the application is closed?

For example, here's my app:

import panel as pn
import param


class Test(param.Parameterized):
    test_number = param.Integer(default=0)


test = Test()

app = pn.template.VanillaTemplate()
app.main.append(test.param)
app.servable()

When I run it with panel serve, I can interact with the application. Once I'm done, I close the browser window. Is there a way to make sure that the panel serve command also exits/stops?


Solution

  • There are scripts for shutting down command prompt from Python, for example this or this SO question. This version of your example shuts down the server, but leaves the command prompt window open:

    import panel as pn
    import param
    
    
    def interrupt(session_context):
        raise KeyboardInterrupt
    
    class Test(param.Parameterized):
        test_number = param.Integer(default=0)
    
    def main():
        test = Test()
    
        app = pn.template.VanillaTemplate()
        app.main.append(test.param)
        app.servable()
        pn.state.on_session_destroyed(interrupt)
        return app
    
    try:
        session = pn.serve(
            {"Test": main},
            port=8000,
            title="Test",
            show=True,
            start=True,
            autoreload=False
        )
    except KeyboardInterrupt:
        pass
    

    I'm sure there is some more elegant way of doing this by using Panel function stop() but I didn't manage to get that working. The idea is to put session.stop() inside the interrupt() function. My environment has some problems with using threaded=True as a parameter to the session. That would supposedly hasten the process. Now it takes quite some time for the server to stop.