Pythonで複数ファイル、複数ディレクトリに分割した処理を呼び出す際に、常に同じ位置からfrom-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ファイル
Python:(main.py)
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()
Python:(print_hello)
def print_hello():
    print("Hello")
main.py:5,6行目
ルートディレクトリに1つ上の階層を指定

main.py:8行目
ルートディレクトリ直下のd_helloをディレクトリとして指定、その中にあるprint_hello.pyファイルをimport


以上

このエントリーをはてなブックマークに追加
コメントを閉じる

コメント

コメントフォーム
記事の評価
  • リセット
  • リセット