ves*_*and 4 python ipython spyder jupyter-notebook
当我尝试学习一些数据科学编码时,我在 Spyder 和 jupyter 笔记本之间切换了一下。因此,我想找到一种方法来判断一个函数是从一个函数还是另一个函数调用,以便我可以停用仅用于笔记本的脚本部分。%matplotlib inline当我从 Spyder 运行代码时,我认为以下类似的内容可以省略该部分:
if __name__ != '__main__':
%matplotlib inline
print('Hello, jupyter')
else:
print('Hello, Spyder')
Run Code Online (Sandbox Code Playgroud)
但__name__ = _main__在这两种情况下,保持%matplotlib inline原样也会在 Spyder 中引发错误建议。
我已经在这里测试了这些建议:如何检查您是否在 Jupyter notebook 中。这有效,但我有点困惑,因为我也在 Spyder 中运行 IPython 控制台。另外,我希望你们中的一些人可能有其他建议!
谢谢!
似乎没有正确或面向未来的方法来实现这一点,但我会使用这种模式:
import os
if "JPY_PARENT_PID" in os.environ:
print('Hello, jupyter')
else:
print('Hello, Spyder')
Run Code Online (Sandbox Code Playgroud)
它比此处给出的答案更具体,副作用更少。它适用于 jupyter notebook 和 jupyter lab,所以我认为可以安全地假设它在一段时间内不会过时。
让我知道它是如何为你工作的。
上述解决方案仅适用于 spyder >3.2
但是,下面的解决方案可能适用于所有版本的 jupyter notebook 或 spyder。基本与上面的 if else 循环相同,但我们只是测试os.environspyder 东西的存在。
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')
Run Code Online (Sandbox Code Playgroud)
这能解决你的问题吗?
| 归档时间: |
|
| 查看次数: |
833 次 |
| 最近记录: |