%matplotlib inline
部分:
if __name__ != '__main__':
%matplotlib inline
print('Hello, jupyter')
else:
print('Hello, Spyder')
但在这两种情况下__name__ = _main__
,并且%matplotlib inline
也是如此,这也会在Spyder中引发错误建议。
我在这里测试了这些建议:How to check if you are in a Jupyter notebook。这是有效的,但我有点困惑,因为我也在Spyder中运行一个IPython控制台。另外,我希望你们中的一些人可能有其他建议!
谢谢!
答案 0 :(得分:4)
似乎没有一个正确的或面向未来的方式来解决此问题,但我会使用这种模式:
import os
if "JPY_PARENT_PID" in os.environ:
print('Hello, jupyter')
else:
print('Hello, Spyder')
它比here给出的答案更具体,副作用更少。它适用于jupyter笔记本以及jupyter实验室,所以我认为可以安全地假设它将在未来证明一段时间。
让我知道它对你有用。
上述解决方案仅适用于spyder> 3.2
但是,下面的解决方案可能适用于所有版本的jupyter笔记本或spyder。基本它是相同的if if从上面循环,但我们只是测试os.environ
是否存在spyder东西。
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')
这能为你解决问题吗?
答案 1 :(得分:0)
我想我找到了一个更简单的解决方案:
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)
如果我在JuyterLab中运行该函数,则输出为:
Code *IS* running in Jupyter platform (notebook, lab, etc.)
在VS Code中,它是:
Code *IS NOT* running in Jupyter platform (notebook, lab, etc.)