ImportError: No module named gspread

Niels Dingsbums picture Niels Dingsbums · Jul 11, 2018 · Viewed 12.8k times · Source

I'm trying to work with the gspread library in python. i installed the lib with pip install gspread but when I run the code:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://sreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('FILE_NAME.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open('Changelog').sheet1
print(wks.get_all_records())

it gives me an error:

File "stuff.py", line 1, in <module>
    import gspread
ImportError: No module named gspread

When I run it in python3 it gives me no import error. But those:

File "stuff.py", line 8, in <module>
    gc = gspread.authorize(credentials)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gspread/__init__.py", line 38, in authorize
    client.login()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gspread/client.py", line 51, in login
    self.auth.refresh(http)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/oauth2client/client.py", line 545, in refresh
    self._refresh(http)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/oauth2client/client.py", line 749, in _refresh
    self._do_refresh_request(http)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/oauth2client/client.py", line 819, in _do_refresh_request
    raise HttpAccessTokenRefreshError(error_msg, status=resp.status)
oauth2client.client.HttpAccessTokenRefreshError: invalid_scope: https://sreadsheets.google.com/feeds is not a valid audience string.

Answer

The Matt picture The Matt · Jul 11, 2018

It is possible that pip install gspread installed gspread to a different python interpreter.

Try the following to reinstall gspread in the python interpreter you want to use.

import sys, subprocess
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'gspread'])

EDIT: The method listed below has been deprecated and only works on Python 2.

import pip
pip.main(["install", "gspread"])