Pythonで複数ファイル、複数ディレクトリに分割した処理を呼び出す際に、常に同じ位置からfrom-importで関数を呼び出すため、ルート位置を初期化する処理について
Python:
"."の部分で現在実行しているファイルからの相対位置でルートディレクトリを指定します。
ディレクトリ構造:
Python:(main.py)
Python:(print_hello)
main.py:5,6行目
ルートディレクトリに1つ上の階層を指定
main.py:8行目
ルートディレクトリ直下のd_helloをディレクトリとして指定、その中にあるprint_hello.pyファイルをimport
以上
ルートディレクトリ指定
Python:
import os
import sys
# Rootディレクトリのパスを取得
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "."))
sys.path.append(parent_dir)
使い方の例 (import)
ディレクトリ構造:
ルートディレクトリ位置
├── d_main
│ └── main.py // 実行ファイル
└── d_hello
└── print_hello.py // importファイル
import sys
import os
# Rootディレクトリのパスを取得
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(parent_dir)
from d_hello import print_hello
# 関数呼び出し
print_hello.print_hello()
def print_hello():
print("Hello")
ルートディレクトリに1つ上の階層を指定
main.py:8行目
ルートディレクトリ直下のd_helloをディレクトリとして指定、その中にあるprint_hello.pyファイルをimport
以上