LoginSignup
0
0

More than 3 years have passed since last update.

sys.path.append('..')しても親ディレクトリにあるモジュールをimportできない

Posted at

問い

  1. Pythonでmain.pyからmodule1.pyを使いたい。
  2. projectディレクトリでpython scripts/main.pyを実行。
ディレクトリ構成
project/
      ├ module/
      │       └ module1.py
      └ scripts/
              └ main.py
main.py
import sys
sys.path.append('..')
from module import module1

このままではModuleNotFoundErrorが出る。

答え

..が示すのは、作業ディレクトリから見た親ディレクトリ。実行ファイルのあるディレクトリではない。つまり、projectディレクトリに対する親ディレクトリを参照している。
解決策としては、モジュールとして実行することが考えられる。

python -m scripts.main
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