【发布时间】:2016-07-14 23:01:06
【问题描述】:
目标
我有一个用 python 编写的脚本。
- 连接数据库
- 插入一些虚假数据
我的目标是每小时执行一次该脚本。
database.py
#!/usr/bin/python
import MySQLdb
import random
import requests
import time
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="*********", # your password
db="db-local") # name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
# The first line is defined for specified vendor
mac = [ 0x00, 0x24, 0x81,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff) ]
device_mac = ':'.join(map(lambda x: "%02x" % x, mac))
cpe_mac = '000D6766F2F6'
url = "https://randomuser.me/api/"
data = requests.get(url).json()
firstname = data['results'][0]['user']['name']['first']
lastname = data['results'][0]['user']['name']['last']
email = data['results'][0]['user']['email']
gender = data['results'][0]['user']['gender']
age_range_options = [">15", "15-25", "25-40","40+"]
age_range = random.choice(age_range_options)
ip = '10.10.10.10'
host_name = 'cron.job'
visit_count = 1
created_at = time.strftime('%Y-%m-%d %H:%M:%S')
updated_at = time.strftime('%Y-%m-%d %H:%M:%S')
sql = ('''INSERT INTO visitors (device_mac,cpe_mac,firstname, lastname, email, gender, age_range,ip,host_name,visit_count,created_at, updated_at) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''')
args = (device_mac,cpe_mac, firstname, lastname, email, gender, age_range,ip, host_name,visit_count, created_at, updated_at)
cur.execute(sql,args)
db.commit()
# for record in records:
# print records
db.close()
CronniX
我做了一些研究,人们建议了一堆应用程序来做到这一点。
所以我尝试下载/安装 CronniX
创建一个任务> 设置计划> 并运行它。
它一直挂在executing ...
任务到黎明
除此之外,我还尝试了Task Till Dawn,并且再次尝试
创建一个任务> 设置计划> 并运行它。
结果
似乎没有任何东西插入到我的数据库中,即使它说成功执行了 35 次。它所做的只是在Xcode 窗口中弹出我的database.py。
终端
我运行python database.py,它工作得非常好,并且数据被插入。
我在想,这是权限问题,但我已经这样做了
sudo chmod a+x database.py
我错过了什么?实现这一目标的更好方法是什么?
任何建议/提示将不胜感激!
【问题讨论】:
-
你试过cron吗?有时简单的解决方案效果最好,而您已经在使用终端...
-
如果我使用 cron 我如何设置/配置它以每 60 分钟运行一次。请告知,与此同时,我会阅读
cron。感谢您的建议。 -
只需在 python 中完成。使用线程并将其休眠一个小时。
-
./database.py是否可以在没有 python 的情况下从终端工作?还有/usr/bin/python database.py -
@cricket_007 :如果我在 python 中完成这一切,我将不得不打开终端,然后输入
python database.py。我正在寻找一些东西,它会在后台自动执行。如果在这里遗漏了什么,请纠正我。
标签: python macos cron cron-task