1
1

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 1 year has passed since last update.

Pythonのimportのパスの扱いがうまく行かない

Posted at

はじめに

久しぶりにPythonを書いていたのですが、毎回Importの仕方で躓くなと感じたのでまとめていきたいと思います

問題

以下のディレクトリ構成があるとします

┣ app
    ┣ main.py
    ┣ driver
        ┣ get_driver.py
    ┣ gateway
        ┣ get_gateway.py
┣ test
    ┣ test_gateway.py

main.pyではgateway.pyを読み込んでいます

main.py
from gateway.get_gateway import GetGateway

main.pyではget_gateway.pyを呼び出します
gateway.pyではget_driver.pyを読み込みます

gateway.py
from driver.get_driver import GetDriver

ここでmain.pyからこのコードを実行するとmain.pyからみてfromのパスは相対パスになっているので問題なく動きます

┣ app
    ┣ main.py ←ここからみてる
    ┣ driver
        ┣ get_driver.py
    ┣ gateway
        ┣ get_gateway.py
┣ test
    ┣ test_gateway.py

しかしtest_gateway.pyget_gateway.pyを直接読み込んで関数を実行しているため相対パス的にdriverがないと言われます

┣ app
    ┣ main.py
    ┣ driver
        ┣ get_driver.py
    ┣ gateway ←ここからみてるので下の階層にdriverはないのでエラー
        ┣ get_gateway.py
┣ test
    ┣ test_gateway.py

このようにテストとmainでインポートがちぐはぐになってしまいました
これをなんとかしたいと思いました

解決方法

インポートのパスをみるときは全部appから見るように設定することで解決しました

$ export PYTHONPATH=/root/src/app

これを実行することでうまく辻褄があうようになりました

私の環境はDockerなので以下のようにしました

docker-compose.yml
version: "3"
services:
  app:
    build: .
    container_name: "app"
    tty: true 
    working_dir: /root/src
    volumes:
      - ./src:/root/src
    environment:
      - PYTHONPATH=/root/src/app

おわりに

地味に躓いてしまいましたがChatGPTのおかげで解決できました
そのうちQiitaも不要になるのではないかと思いました

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?