Reputation: 61184
I'm switching a bit between Spyder and jupyter notebooks when I'm trying to learn some coding for data science. Therefore I'd like to find a way to tell whether a function is being called from one or the other so I can deactivate parts of the script that are meant for notebooks only. I thought something like the following would work to leave out the %matplotlib inline
part when I'm running the code from Spyder:
if __name__ != '__main__':
%matplotlib inline
print('Hello, jupyter')
else:
print('Hello, Spyder')
But __name__ = _main__
in both cases, and leaving %matplotlib inline
as is also raises an error suggestion in Spyder.
I've tested the suggestions here: How to check if you are in a Jupyter notebook. That works, but I am a bit puzzled since I'm running an IPython console in Spyder as well. Also, I'm hoping that some of you may have other suggestions!
Thank you!
Upvotes: 7
Views: 1702
Reputation: 119
I think I found a simpler solution:
def test_ipkernel():
import sys
which = 'IS' if 'ipykernel_launcher.py' in sys.argv[0] else 'IS NOT'
msg = f'Code *{which}* running in Jupyter platform (notebook, lab, etc.)'
print(msg)
If I run the function in JuyterLab, the output is:
Code *IS* running in Jupyter platform (notebook, lab, etc.)
In VS Code, it is:
Code *IS NOT* running in Jupyter platform (notebook, lab, etc.)
Upvotes: 2
Reputation: 5310
There doesn't seemed be a correct or future-proof way to pull this off but I would use this pattern:
import os
if "JPY_PARENT_PID" in os.environ:
print('Hello, jupyter')
else:
print('Hello, Spyder')
It's a little bit more specific and has less side-effects than the answer given here. It works in jupyter notebook as well as jupyter lab so I think it is safe to assume that it will future-proofish for a while.
Let me know how it works for you.
The solution above only works in spyder >3.2
However the solution below should work for all versions of jupyter notebook or spyder, maybe. Basic it's the same if else loop from above but we just test the os.environ
for the presence of spyder stuff.
import os
# spyder_env: was derived in spyder 3.2.8 ipython console running:
# [i for i in os.environ if i[:3] == "SPY"]
spyder_env = set(['SPYDER_ARGS',
'SPY_EXTERNAL_INTERPRETER',
'SPY_UMR_ENABLED',
'SPY_UMR_VERBOSE',
'SPY_UMR_NAMELIST',
'SPY_RUN_LINES_O',
'SPY_PYLAB_O',
'SPY_BACKEND_O',
'SPY_AUTOLOAD_PYLAB_O',
'SPY_FORMAT_O',
'SPY_RESOLUTION_O',
'SPY_WIDTH_O',
'SPY_HEIGHT_O',
'SPY_USE_FILE_O',
'SPY_RUN_FILE_O',
'SPY_AUTOCALL_O',
'SPY_GREEDY_O',
'SPY_SYMPY_O',
'SPY_RUN_CYTHON',
'SPYDER_PARENT_DIR'])
# Customize to account for spyder plugins running in jupyter notebook/lab.
n = 0
if "JPY_PARENT_PID" in os.environ:
# Compare the current os.environ.keys() to the known spyder os.environ.
overlap = spyder_env & set(os.environ.keys())
if len(overlap) == n:
print('Hello, jupyter')
# This could be a more specific elif statment if needed.
else:
print('Hello, Spyder')
Does that solve the problem for you?
Upvotes: 8