2

I want to use python code for Bokeh server and use it as library as well. So I modularize my code by _name_=='__main__', but standalone Bokeh server is not getting triggered.

def initialize_WatchDataFrame():

     print("Initialize Watchlist")

if __name__ == "__main__":       

    initialize_WatchDataFrame()

    curdoc().add_periodic_callback(update_WatchDataFrame, 2000)
    curdoc().title = "WatchList"

So when i was running the server with "bokeh serve Watchlist.py". I dont see the call to initialize_WatchDataFrame() being made.

Niels Henkens
  • 2,553
  • 1
  • 12
  • 27
Pushkar
  • 61
  • 4

1 Answers1

0

If you want to be able to run python foo.py and don't want to run bokeh serve foo.py then you you will have to embed the Bokeh server as library. That requires setting up and starting a Tornado IOLoop manually yourself. Here is a complete example:

from bokeh.plotting import figure
from bokeh.server.server import Server
from tornado.ioloop import IOLoop

def modify_doc(doc):
    p = figure()
    p.line([1,2,3,4,5], [3,4,2,7,5], line_width=2)
    doc.add_root(p)

if __name__ == '__main__':
    server = Server({'/bkapp': modify_doc}, io_loop=IOLoop())
    server.start()
    server.io_loop.start()

Depending on what you are trying to accomplish, you may also need to embed this app using server_document, or run the IOLoop in a thread. Those use cases are demonstrated in the examples linked in the docs.

It probably also bears mentioning: the code that modifies the document only runs when a browser connection is made. (And: it is run every time a browser connection is made, to generate a new document just for that session.)

bigreddot
  • 33,642
  • 5
  • 69
  • 122
  • Thanks for the response ! How does one embed this code above, when i try to run this i get "RuntimeError: Cannot run the event loop while another loop is running" – Pushkar Apr 29 '19 at 02:05
  • Even when i am running https://github.com/bokeh/bokeh/blob/1.1.0/examples/howto/server_embed/standalone_embed.py example i am getting error RuntimeError: This event loop is already running – Pushkar Apr 29 '19 at 02:10
  • Make sure you have a recent version of Tornado. – bigreddot Apr 29 '19 at 06:33