簡體   English   中英

如何判斷是否正在從 jupyter notebook 調用函數?

[英]How to tell whether a function is being called from a jupyter notebook or not?

當我嘗試學習一些數據科學編碼時,我在 Spyder 和 jupyter 筆記本之間切換了一下。 因此,我想找到一種方法來判斷一個函數是從一個函數還是另一個函數調用,以便我可以停用僅適用於筆記本的腳本部分。 當我從 Spyder 運行代碼時,我認為以下類似的東西%matplotlib inline部分:

if __name__ != '__main__':
    %matplotlib inline
    print('Hello, jupyter')
else:
    print('Hello, Spyder')

但是__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')

它比此處給出的答案更具體,副作用更少。 它適用於 jupyter notebook 和 jupyter lab,所以我認為可以安全地假設它在一段時間內不會過時。

讓我知道它是如何為你工作的。

更新:

上述解決方案僅適用於 spyder >3.2

但是,下面的解決方案可能適用於所有版本的 jupyter notebook 或 spyder。 基本與上面的 if else 循環相同,但我們只是測試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')

這能解決你的問題嗎?

我想我找到了一個更簡單的解決方案:

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.)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM