簡體   English   中英

Python Jupyter Notebook 中的相對導入

[英]Python Relative Import in Jupyter Notebook

假設我有以下結構:

 dir_1
 ├── functions.py
 └── dir_2
     └── code.ipynb

code.ipynb中,我只想訪問functions.py中的 function 並試過這個:

from ..functions import some_function

我收到錯誤:

attempted relative import with no known parent package

我已經檢查了一堆類似的帖子,但還沒有弄清楚......我正在從 conda conda env運行 jupyter 筆記本,我的 python 版本是3.7.6

給定這樣的結構:

 dir_1
 ├── functions
 │   └──__init__.py  # contains some_function
 └── dir_2
     └── code.ipynb

我們只是在sys.path中插入一個相對路徑:

import sys

if ".." not in sys.path:
    sys.path.insert(0, "..")
from functions import some_function

在你的筆記本上做:

import os, sys
dir2 = os.path.abspath('')
dir1 = os.path.dirname(dir2)
if not dir1 in sys.path: sys.path.append(dir1)
from functions import some_function

您可以使用sys.path.append('/path/to/application/app/folder')然后嘗試導入

jupyter notebook 從 sys.path 中的當前工作目錄開始。 sys.path

...包含用於調用 Python 解釋器的腳本的目錄。

如果您的實用程序函數位於父目錄中,您可以執行以下操作:

import os, sys
parent_dir = os.path.abspath('..')
# the parent_dir could already be there if the kernel was not restarted,
# and we run this cell again
if parent_dir not in sys.path:
    sys.path.append(parent_dir)
from functions import some_function

暫無
暫無

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

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