Issue
I want my function to do one thing if it's called from the IPython notebook and another thing if its called from a console or library code. In particular I'm making a progress bar with the desired following behavior:
- Notebook: Immediately return a widget
- Console: Block and dump information to
sys.stdout
Is there a flag somewhere I can check to determine if the user called my function from a notebook or otherwise?
Solution
You can't detect that the frontend is a notebook with perfect precision, because an IPython Kernel can have one or more different Jupyter frontends with different capabilities (terminal console, qtconsole, notebook, etc.). You can, however, identify that it is a Kernel and not plain terminal IPython:
import sys
def is_kernel():
if 'IPython' not in sys.modules:
# IPython hasn't been imported, definitely not
return False
from IPython import get_ipython
# check for `kernel` attribute on the IPython instance
return getattr(get_ipython(), 'kernel', None) is not None
Since the notebook is so much more popular than other frontends, this indicates that the frontend is probably a notebook, but not conclusively. So you want to be sure there's a way out for the more primitive frontends.
Answered By - minrk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.