簡體   English   中英

從另一個 jupyter notebook 導入函數

[英]importing functions from another jupyter notebook

我正在嘗試從另一個 jupyter 筆記本導入一個函數

在 n1.ipynb 中:

def test_func(x):
  return x + 1
-> run this

在 n2.ipynb 中:

%%capture
%%run n1.ipynb
test_func(2)

錯誤:

NameError Traceback (most recent call last)<ipython-input-2-4255cde9aae3> in <module>()
----> 1 test_func(1)

NameError: name 'test_func' is not defined

請問有什么簡單的方法可以做到嗎?

nbimporter 模塊可以幫助我們:

pip install nbimporter

例如,在此目錄結構中有兩個筆記本:

/src/configuration_nb.ipynb

分析.ipynb

/src/configuration_nb.ipynb:

class Configuration_nb():
    def __init__(self):
        print('hello from configuration notebook')

分析.ipynb:

import nbimporter
from src import configuration_nb

new = configuration_nb.Configuration_nb()

輸出:

Importing Jupyter notebook from ......\src\configuration_nb.ipynb
hello from configuration notebook

我們還可以從 python 文件導入和使用模塊。

/src/configuration.py

class Configuration():
    def __init__(self):
        print('hello from configuration.py')

分析.ipynb:

import nbimporter
from src import configuration

new = configuration.Configuration()

輸出:

hello from configuration.py

我為將函數導入 Jupyter 筆記本所做的工作是在單獨的 Python .py 文件中編寫函數,然后在筆記本中使用魔術命令 %run。 以下是至少一種方法的示例:

notebook.ipynb 和 helper_functions.py 都在同一目錄中。

helper_functions.py:

def hello_world():
    print('Hello world!')

筆記本.ipynb:

%run -i helper_functions.py
hello_world()

notebook.ipynb 輸出:

Hello world!

%run 命令告訴筆記本運行指定的文件, -i 選項在 IPython 命名空間中運行該文件,這在這個簡單示例中沒有真正意義,但如果您的函數與筆記本中的變量交互,則很有用。 如果我沒有為您提供足夠的詳細信息,請查看文檔

對於它的價值,我還嘗試在外部 .ipynb 文件而不是外部 .py 文件中運行函數定義,它對我有用。 如果您想將所有內容都保存在筆記本中,可能值得探索。

暫無
暫無

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

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