我遇到了一個我試圖在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