Search code examples
pythonvpython

What is the output of a VPython Script? Why does it open in Chrome for me?


Whenever I run a script using the vpython library, the visualization opens in a google chrome tab.

I want to know why this is the case, and what the output of the vpython visualization is that would make it open in a Chrome tab.


Solution

  • Well, if you open site-packages/vpython/no_notebook.py, you will see:

    import webbrowser as _webbrowser
    

    So that's that.

    Under the hood, what it does in "no jupyter notebook mode" is that it starts a threaded local HTTP server that serves up some javascript, and then open a page in your web browser to connect to that server. The rest is just exchange of data between the server and the client, like any other web application.

    A more detailed explanation of the data exchange can be found in site-packages/vpython/vpython.py:

    # Now there is no threading in Jupyter VPython. Data is sent to the
    # browser from the trigger() function, which is called by a
    # canvas_update event sent to Python from the browser (glowcomm.js), currently
    # every 33 milliseconds. When trigger() is called, it immediately signals
    # the browser to set a timeout of 33 ms to send another signal to Python.
    # Note that a typical VPython program starts out by creating objects (constructors) and
    # specifying their attributes. The 33 ms signal from the browser is adequate to ensure
    # prompt data transmissions to the browser.
    
    # The situation with non-notebook use is similar, but the http server is threaded,
    # in order to serve glowcomm.html, jpg texture files, and font files, and the
    # websocket is also threaded.
    
    # In both the notebook and non-notebook cases output is buffered in baseObj.updates
    # and sent as a block to the browser at render times.
    

    Honestly, I don't think the model of vpython is a good API model (for one thing, it's awkward to use from a normal interactive shell), but I guess it works.