I am having a problem with the python script that I am trying to automate in cron. I belive that the problem is in the mysql module not being imported when running the script through cron.
I tried different solution in the net but none of them seems to be working.
Btw, the script is running normal when executing in terminal
Here is my 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
and here is the error generated in 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
and here is the part of the script that causing the error:
#!/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()
Thanks
try-suite. Socursorwas not successfully defined. The error message should have been printed in/var/log/test.log. What does it say?try,except,finallylines, dedent the code inside and just run the code "bare"? Then you should see intest.logthe traceback error message of the true originating exception.try,except,finally. The problem is in the mysql_connector.py. I wasn't able to defined the config file using its absolute path. Thank you @unutbu