内容へ移動
fl8 Wiki
ユーザ用ツール
ログイン
サイト用ツール
検索
ツール
文書の表示
以前のリビジョン
バックリンク
最近の変更
メディアマネージャー
サイトマップ
ログイン
>
最近の変更
メディアマネージャー
サイトマップ
現在位置:
Dokuwiki.fl8.jp
»
15_python
»
05 上の階層からimport
トレース:
15_python:05_import_from_parent_dir
この文書は読取専用です。文書のソースを閲覧することは可能ですが、変更はできません。もし変更したい場合は管理者に連絡してください。
====== 05 上の階層からimport ====== 以下の構成でmain.pyからmod1.pyをimportしたい # tree . ├── conf │ └── mod1.py ├── item │ └── main.py ===== 失敗パターン ===== <code|main.py> from ..conf import mod1 if __name__ == '__main__': print(mod1.MOD) </code> エラー <code> # python3.6 item/main.py Traceback (most recent call last): File "item/main.py", line 1, in <module> from ..conf import mod1 ValueError: attempted relative import beyond top-level package </code> ===== 成功パターン ===== Pythonから一つ上の通常では階層はアクセスできないので osでディレクトリを取得 sysでライブラリのインポートパスを追加する <code|main.py> currnet_dir = os.path.dirname( os.path.abspath(__file__) ) sys.path.append(currnet_dir + '/../') from conf import mod1 if __name__ == '__main__': print(mod1.MOD) </code> {{tag>Python}}
15_python/05_import_from_parent_dir.txt
· 最終更新: 2019/08/22 08:00 by
matsui
ページ用ツール
文書の表示
以前のリビジョン
バックリンク
文書の先頭へ