티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

Jupyter Notebook에서 상대경로로 다른 디렉토리 모듈의 로컬 함수 사용하기

 문제 내용 

I have a directory structure similar to the following

다음과 유사한 디렉토리 구조를 가지고 있습니다.
meta_project
    project1
        __init__.py
        lib
            module.py
            __init__.py
    notebook_folder
        notebook.jpynb

 

When working in notebook.jpynb if I try to use a relative import to access a function function() in module.py with:

notebook.jpynb에서 작업할 때, 상대 경로로 import하여 module.py에 있는 function()에 액세스하려고 하면:
from ..project1.lib.module import function

 

I get the following error:

다음 오류가 발생합니다.

 

SystemError                               Traceback (most recent call last)
<ipython-input-7-6393744d93ab> in <module>()
----> 1 from ..project1.lib.module import function

SystemError: Parent module '' not loaded, cannot perform relative import

 

Is there any way to get this to work using relative imports?

상대경로 import하여 이것을 작동시킬 수 있는 방법이 있나요?

 

Note, the notebook server is instantiated at the level of the meta_project directory, so it should have access to the information in those files.

노트북 서버는 meta_project 디렉터리 수준에서 인스턴스화되므로 해당 파일의 정보에 액세스할 수 있어야 합니다.

 

Note, also, that at least as originally intended project1 wasn't thought of as a module and therefore does not have an __init__.py file, it was just meant as a file-system directory. If the solution to the problem requires treating it as a module and including an __init__.py file (even a blank one) that is fine, but doing so is not enough to solve the problem.

또한, 적어도 원래 의도했던 것처럼 프로젝트1은 모듈로 생각되지 않았고 따라서 __init_.py 파일을 가지고 있지 않으며, 파일 시스템 디렉터리로 의미했을 뿐이다. 문제에 대한 해결책이 모듈로 처리하고 __init_.py 파일(빈 파일이라도)을 포함해야 하는 경우에는 문제를 해결하기에 충분하지 않습니다.

 

I share this directory between machines and relative imports allow me to use the same code everywhere, & I often use notebooks for quick prototyping, so suggestions that involve hacking together absolute paths are unlikely to be helpful.

나는 이 디렉토리를 기계 간에 공유하고 관련 가져오기를 통해 어디서나 동일한 코드를 사용할 수 있으며, 빠른 프로토타이핑을 위해 노트북을 자주 사용하기 때문에 절대 경로를 함께 해킹하는 것과 관련된 제안은 도움이 되지 않을 것이다.

 


Edit: This is unlike Relative imports in Python 3, which talks about relative imports in Python 3 in general and – in particular – running a script from within a package directory. This has to do with working within a jupyter notebook trying to call a function in a local module in another directory which has both different general and particular aspects.

편집: 일반적으로 파이썬 3의 상대경로 import에 대해 이야기하는 Relative imports in Python 3 달리, 특히 패키지 디렉터리 내에서 스크립트를 실행하는 것에 대해 이야기한다. 이것은 일반적인 측면과 특정한 측면이 모두 다른 다른 디렉토리의 로컬 모듈의 함수를 호출하려는 주피터 노트북 내에서 작업하는 것과 관련이 있다.

 

 

 

 높은 점수를 받은 Solution 

I had almost the same example as you in this notebook where I wanted to illustrate the usage of an adjacent module's function in a DRY manner.

저는 이 노트북에서 당신과 거의 동일한 예를 가지고 있습니다. DRAY 방식으로 인접 모듈의 기능을 사용하는 방법을 설명하고 싶었습니다.

 

My solution was to tell Python of that additional module import path by adding a snippet like this one to the notebook:

내 해결책은 노트북에 다음과 같은 스니펫을 추가하여 Python에게 추가 모듈 가져오기 경로를 알려주는 것이었다.
import os
import sys
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
    sys.path.append(module_path)

 

This allows you to import the desired function from the module hierarchy:

이를 통해 모듈 계층에서 원하는 기능을 가져올 수 있습니다.
from project1.lib.module import function
# use the function normally
function(...)

 

Note that it is necessary to add empty __init__.py files to project1/ and lib/ folders if you don't have them already.

빈 __init_.py 파일을 project1/ 및 lib/ 폴더에 추가해야 합니다.

 

 

 

 가장 최근 달린 Solution 

If you are working via the Jupyter extension in VS Code, I found that you can now set this path in your settings.json file.

VS Code에서 Jupyter 확장을 통해 작업하는 경우 settings.json 파일에서 이 경로를 설정할 수 있습니다.
{
    "jupyter.notebookFileRoot": "/path/to/your/module/root"
}

 

Edit: Or, to set it at your workspace root more generically:

편집: 또는 작업영역 루트를 보다 일반적으로 설정하려면:
{
    "jupyter.notebookFileRoot": "${workspaceFolder}"
}

 

 

출처 : https://stackoverflow.com/questions/34478398/import-local-function-from-a-module-housed-in-another-directory-with-relative-im

반응형
댓글
공지사항
최근에 올라온 글