0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonでimport時の「attempted relative import beyond top-level package」の解決方法

Posted at

エラー概要

以下のようなディレクトリ構成で

root/
 ├ core/
 │ └ base.py
 │ 
 ├ sub/
 │ └ subA.py

subA.pyからbase.pyを呼び出そうする。

sub.py
from ..core.base import *

すると以下のエラーが発生する

Exception Value: attempted relative import beyond top-level package

原因は「Pythonは実行するファイルのカレントディレクトリを最上位のルートディレクトリとして使用」という仕様があり、上位のディレクトリに移動できないため発生。

解決方法

環境変数のPYTHONPATHを設定すればよい。

export PYTHONPATH=/root

そしてコードを以下のように修正

sub.py
from core.base import *

これでpython実行時にパッケージ検索パスに/rootが加わるため、/rootから配下のディレクトリを探すことが出来る。

参考:https://docs.python.org/ja/3/using/cmdline.html#envvar-PYTHONPATH

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?