python - 如果从 cron 作业执行,python 不写入文件
问题描述
我编写了一个 python 脚本,它从谷歌分析 API 获取一些数据,然后将这些值写入 webroot 文件夹中的 JSON 文件。我的脚本运行良好,并在我直接或通过 ./analytics.py 执行时写入 JSON 文件。我在 Ubuntu 18.04 上。
我通过以下方式使其可执行:
chmod +x analytics.py
并在我的代码开头添加了shebang:
#!/usr/bin/env python3
我的 crontab -e 条目如下所示:
45 17 * * * /root/dashboard_scripts/analytics.py
tail -f /var/log/syslog的输出如下:
Apr 17 15:44:01 gs-kpi cron[62390]: (root) RELOAD (crontabs/root)
Apr 17 15:45:01 gs-kpi CRON[63978]: (root) CMD (/root/dashboard_scripts/analytics.py)
如果 cron 在用户 root 下运行,我还检查了一个示例 cron。
我的python脚本是这样的:
#!/usr/bin/env python3
import argparse
import json
import re
import os
import pprint
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
save_path = '/var/www/html/'
filename = 'googleanalytics_data.json'
data = []
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
DISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest')
KEY_FILE_LOCATION = '543671d681ee.p12'
SERVICE_ACCOUNT_EMAIL = 'data-gserviceaccount.com'
VIEW_ID = '10'
def initialize_analyticsreporting():
"""Initializes an analyticsreporting service object.
Returns:
analytics an authorized analyticsreporting service object.
"""
credentials = ServiceAccountCredentials.from_p12_keyfile(
SERVICE_ACCOUNT_EMAIL, KEY_FILE_LOCATION, scopes=SCOPES)
http = credentials.authorize(httplib2.Http())
# Build the service object.
analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)
return analytics
def get_report(analytics):
# Use the Analytics Service Object to query the Analytics Reporting API V4.
return analytics.reports().batchGet(
body={
'reportRequests': [
{
'viewId': VIEW_ID,
'dateRanges': [
{'startDate': '7daysAgo', 'endDate': 'yesterday'},
{'startDate': '14daysAgo', 'endDate': '8daysAgo'},
],
'metrics': [
{'expression': 'ga:pageviews'},
{'expression': 'ga:sessions'},
{'expression': 'ga:pageviewsPerSession'},
{'expression': 'ga:bounces'},
{'expression': 'ga:users'},
{'expression': 'ga:newUsers'},
{'expression': 'ga:goal7Starts'},
{'expression': 'ga:avgPageLoadTime'}
],
"orderBys": [
{"fieldName": "ga:pageviews", "sortOrder": "DESCENDING"}
]
}
]
}
).execute()
def print_response(response):
"""Parses and prints the Analytics Reporting API V4 response"""
for report in response.get('reports', []):
columnHeader = report.get('columnHeader', {})
dimensionHeaders = columnHeader.get('dimensions', [])
metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
rows = report.get('data', {}).get('rows', [])
for row in rows:
dimensions = row.get('dimensions', [])
dateRangeValues = row.get('metrics', [])
for header, dimension in zip(dimensionHeaders, dimensions):
data.append ( header + ': ' + dimension )
for i, values in enumerate(dateRangeValues):
data.append ('Date range (' + str(i) + ')' )
for metricHeader, value in zip(metricHeaders, values.get('values')):
data.append ( metricHeader.get('name') + ': ' + value )
def main():
analytics = initialize_analyticsreporting()
response = get_report(analytics)
print_response(response)
keys = []
values = []
counter = 0
for item in data:
try:
key = re.search(r'ga:(.*?):', item).group()
value = re.search(r'\d{4,5}', item).group()
counter +=1
if counter > 7:
keys.append(key + '_7days')
else:
keys.append(key + '_14days')
values.append(value)
except:
pass
ga_dict = dict(zip(keys, values))
# print(ga_dict)
with open(os.path.join(save_path, filename), mode='w') as f:
f.write(json.dumps(ga_dict, indent=2))
if __name__ == '__main__':
main()
解决方案
推荐阅读
- image - Vue Bootstrap img 未从资产文件夹中显示
- c - C:将矩形切成正方形的算法
- php - 使用 cURL 对 PHP 进行 C++ 身份验证
- android - 如果我的 minSdkVersion=21,如何使用没有支持/appcompact 库的工具栏?
- javascript - 如何允许 Vue 组件管理自己的转换?
- php - 如何分别获取键和值
- javascript - React native toLocaleDateString 在 Android 上的行为不同
- php - 查询指示不希望的事件
- sql - 在这种情况下如何使用 SUM?
- ajax - 使用ajax php结果的淘汰赛数据绑定不起作用