1

I have a script that I want to run with bokeh serve to display and evaluate results, but I also want to be able to run the same script without bokeh. There's some internal logic that depends on which mode it's running, so I need to be able tot test if the script is launched with bokeh serve or without.

I tried evaluating curdoc(), assuming that when run without bokeh serve it would return None, but in both cases it returns some object, so I can't simply do an if curdoc().

So far I didn't find any reference to this kind of test in the bokeh docs.

vicmortelmans
  • 616
  • 6
  • 16

1 Answers1

2

You can check if an application is being run though a bokeh server by inspecting the __name__ of the file.

If I have an app.py file that I can run either via boke serve --show app.py or python app.py. Depending on how the script is run, the __name__ will be different.

app.py

if __name__.startswith('bokeh'):
    print(__name__, 'running via bokeh server')

else:
    print(__name__, 'not running via bokeh server')

enter image description here

Cameron Riddell
  • 10,942
  • 9
  • 19
  • 2
    When app code is run, a new module object is created for it to run in, and the module gets a name like `bokeh_`. I would caution that this is internal, undocumented behavior, however. We don't have any plans to change it but I can't guarantee it won't ever change, either. I'd encourage someone to submit a [GitHub issue](https://github.com/bokeh/bokeh/issues) regarding the addition of a documented, supported API for this use-case. – bigreddot Jul 25 '22 at 21:25
  • this is helpful and useful enough for development scripts. sometimes `python app.py` is needed and sometimes `bokeh serve --show app.py` is better. – Marc Compere Sep 05 '22 at 22:00