Tocyukiのブログ

ギターと柔術とプログラミングが好き!

Pythonでインストールされているはずのpipモジュールが読み込みできない場合の対処

boto3を使ってデプロイスクリプトを作成していたら、インストールされているはずのboto3が読み込みできないというエラーが発生

$ python3 test.py
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    import boto3
ModuleNotFoundError: No module named 'boto3'

確認してみると、やはりしっかりとインストールされている

$ pip3 show boto3
Name: boto3
Version: 1.14.34
Summary: The AWS SDK for Python
Home-page: https://github.com/boto/boto3
Author: Amazon Web Services
Author-email: UNKNOWN
License: Apache License 2.0
Location: /usr/local/lib/python3.7/site-packages
Requires: botocore, jmespath, s3transfer
Required-by: 

モジュール読み込みパスが足りていないじゃないのかと疑い、以下のスクリプトを作成し確認

import sys
import pprint
pprint.pprint(sys.path)

やはりLocation: /usr/local/lib/python3.7/site-packagesがないことが判明

['/Users/{USERNAME}/.ghq/repository_path',
 '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python37.zip',
 '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7',
 '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/lib-dynload',
 '/Users/{USERNAME}/Library/Python/3.7/lib/python/site-packages',
 '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/site-packages']

なんでこんなことが起こるのかまでは調べられてないけど、とりあえず、環境変数PYTHONPATHにLocationで表示されたパスを追加したらエラーは出なくなったのでよしとしようw

export PYTHONPATH='/usr/local/lib/python3.7/site-packages:$PYTHONPATH'  

後日談

python2系を動かすとエラーとなってしまったので、やはり根本解決にはなっていない模様

Your PYTHONPATH points to a site-packages dir for Python 3.x but you are running Python 2.x!
     PYTHONPATH is currently: "/usr/local/lib/python3.7/site-packages:$PYTHONPATH"
     You should `unset PYTHONPATH` to fix this.