我遇到了一个我试图在cron中自动运行的python脚本的问题。我相信,当通过cron运行脚本时,mysql模块中的问题不会被导入。Python脚本在cron中无法正确执行
我在网络上尝试过不同的解决方案,但他们都没有工作。
顺便说一下,在终端
这里执行时,脚本运行正常是我的crontab:
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin:$HOME/bin
PYTHONPATH=/usr/lib/python2.7/site-packages
#MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
* * * * * /usr/bin/python /var/www/html/testlist.py > /var/log/test.log 2>&1
,这里是在test.log中生成
Traceback (most recent call last):
File "/var/www/html/testlist.py", line 106, in <module>
if __name__ =='__main__':main()
File "/var/www/html/testlist.py", line 104, in main
get_ec2_instances('us-west-1')
File "/var/www/html/testlist.py", line 90, in get_ec2_instances
insert_metric(d[u'Timestamp'],d[u'Average'],d[u'Unit'])
File "/var/www/html/testlist.py", line 49, in insert_metric
cursor.close()
UnboundLocalError: local variable 'cursor' referenced before assignment
这里的错误是导致错误的脚本的一部分:
#!/usr/bin/python
import argparse
import boto.ec2
import boto.ec2.cloudwatch
import datetime
import json
import ast
import sys
sys.path.append('/usr/lib/python2.7/site-packages')
from mysql.connector import MySQLConnection, Error
from mysql_connect import read_db_config
def insert_metric(timestamp,average,unit):
print "Inserting now"
query = "INSERT INTO metrics_tbl(timestamp,average,unit) " \
"VALUES(%s,%s,%s)"
args = (timestamp,average,unit)
try:
db_config = read_db_config()
conn = MySQLConnection(**db_config)
cursor = conn.cursor()
cursor.execute(query, args)
if cursor.lastrowid:
print('last insert id', cursor.lastrowid)
else:
print('last insert id not found')
conn.commit()
except Error as error:
print(error)
finally:
cursor.close()
conn.close()
谢谢
'try'套件发生异常。所以'cursor'没有被成功定义。错误信息应该已经打印在'/ var/log/test.log'中。它说什么? – unutbu
错误发布在上方。它是关于UnboundLocalError:在赋值之前引用的局部变量“游标”。我在模拟时遇到同样的错误,删除导入mysql.connector,然后在shell中执行脚本。 – ChaosDarky
如果你删除'try',''except','finally'行,会在里面放入代码并且只是运行代码“裸”会发生什么?然后你应该在'test.log'中看到真正的原始异常的回溯错误消息。 – unutbu