【发布时间】:2015-04-12 06:20:54
【问题描述】:
我的 python 脚本(如果需要创建)并将一行插入到 sqlite 数据库中。它在手动运行时完美运行,但在由 cron 运行时却不行。当由 cron 运行时,它将创建没有模式的 db 文件,也不会插入行。
另外,命令是在我普通用户的crontab中设置的,但是空的db文件归root所有。
这是我的 crontab 中的行:
0/3 * * * * /home/ubuntu/fullstack/scrape.py
这是python脚本:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#file scrape.py
import urllib2
import json
import datetime
import time
import sqlite3
from datetime import timedelta
response = urllib2.urlopen('http://api.ihackernews.com/page')
res = response.read()
date = response.info()['date']
# Sun, 19 Oct 2014 17:58:01 GMT
datetime = datetime.datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %Z')
datetime = datetime - timedelta(hours=5)
timestamp = int(time.mktime(datetime.timetuple()))
response.close()
res = json.loads(res)
title = res['items'][0]['title']
url = res['items'][0]['url']
points = res['items'][0]['points']
db = sqlite3.connect('/home/ubuntu/fullstack/interval_data.db')
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS data(id INTEGER PRIMARY KEY NOT NULL UNIQUE, title TEXT, url TEXT, points INTEGER, timestamp INTEGER, datetime TEXT);
''')
db.commit()
cursor.execute('''INSERT INTO data(title, url, points, timestamp, datetime)
VALUES(?, ?, ?, ?, ?);''', (title, url, points, timestamp, datetime.strftime('%d %b %Y, %I:%M %p %z')))
db.commit()
db.close()
【问题讨论】: