Pipenv安装google-analytics后无法找到模块求助
问题解决:Pipenv环境下导入googleanalytics报错ModuleNotFoundError
问题原因
你安装的googleanalytics包是为Python 2设计的,在Python 3(包括3.10)中,包内模块的导入规则发生了变化:
- Python 2允许直接
import utils这种隐式相对导入 - Python 3要求显式相对导入(用
from . import xxx)或完整包路径导入,否则会把utils当成顶级模块去查找,导致找不到
另外这个包已经多年未维护,本身不兼容Python 3.x版本。
解决方案
方案1:临时修改包内导入语句(不推荐长期使用)
找到.../site-packages/googleanalytics/__init__.py文件,将第一行的导入代码:
import utils, account, columns, errors, oauth, query
修改为:
from . import utils, account, columns, errors, oauth, query
保存后重新尝试导入即可。
方案2:使用官方维护的替代包(推荐)
放弃googleanalytics这个过时包,直接用你已经安装的google-api-python-client来操作Google Analytics,示例代码:
from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials # 配置认证范围和密钥文件 SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] KEY_FILE_LOCATION = 'path/to/your/service-account-key.json' # 构建认证对象 credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES) # 构建Analytics服务 analytics = build('analyticsreporting', 'v4', credentials=credentials) # 后续调用API示例 response = analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': 'YOUR_VIEW_ID', 'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}], 'metrics': [{'expression': 'ga:sessions'}] } ] } ).execute()
方案3:降级Python版本(不推荐)
如果必须使用googleanalytics包,可以在Pipenv中指定Python 2.7版本,但Python 2已经停止维护,存在安全风险,不建议采用。
内容的提问来源于stack exchange,提问作者paulchoix
相关产品推荐
相关产品推荐

