簡體   English   中英

在 Jupyter Notebook 中,從另一個筆記本執行功能的最佳方式是什么?

[英]In Jupyter Notebook, what is the best way to execute a function from another notebook?

我是 Jupyter Notebooks 的新手,並且使用 Python 3.7 的 Anaconda 安裝。 從另一個筆記本執行功能的最佳方法是什么? 我在這里找到了這個 2 歲的答案,但我不知道是否有新的/更好的方法來安裝 Anaconda(nbimporter 必須單獨安裝,它不在 Anaconda 中)。

這是筆記本中的代碼/信息:

嘗試 #1(失敗)

# working directory files:
# mytest.ipynb # this contains the function I am trying to call
# Untitled.ipynb # this is the Notebook I am working in


# mytest.ipynb contents:
def testfcn(x):
    return print("input is", str(x))


# Untitled.ipynb contents:
from mytest import testfcn
testfcn(4)

ModuleNotFoundError: No module named 'mytest'

嘗試#2(好吧,不理想)

# Untitled.ipynb contents:

%run mytest.ipynb
testfcn(4)

# returns this, extra stuff:
0.019999999999999997
<class 'float'>
input is 4

此處的討論包括 MEdwin 關於如何從您的筆記本中運行另一個筆記本的評論,然后您將能夠在運行%run other_notebook.ipynb步驟的筆記本中調用另一個筆記本的功能。
更新:我剛剛遇到了子筆記本項目,它可以讓您像調用 Python 函數一樣運行筆記本,傳遞參數並返回結果,包括輸出內容。 在這種情況下可能有用。 更新結束。

此外,對於 Python 函數,您不想執行return print 您要么刪除return並保留print部分,要么返回然后可以打印的字符串。

暫無
暫無

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

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