Python脚本在cron中无法正确执行
我遇到了一个我试图在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()
谢谢
你看了回溯吗?问题很明显:在finally
子句中,您尝试访问名称cursor
,但它尚未定义。
看看你的代码:你在try
块的第三行定义cursor
- 所以,直到你的代码到这一点,这个名字cursor
不存在。现在,如果两个第一陈述人提出和异常,你最终在finally
块,在您尝试访问cursor
......
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
(和conn
)。
首先,从try块中提取对read_db_config
的调用 - 这里不需要它。如果失败了,你会有一个回溯...然后在try块之前定义conn
和cursor
到None
,这样你在finally块中没有NameError
,并且在finally块中测试是否为cursor
和在关闭它们之前已经打开。此外,您except
条款是比无用 - 它阻止你获得完整回溯(这是非常宝贵的调试),所以只是将其删除,并让异常繁殖:
conn = None
cursor = None
db_config = read_db_config()
try:
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()
finally:
if cursor is not None:
cursor.close()
if conn is not None:
conn.close()
现在你可以再次运行代码并且这次找出真正的问题是什么(这显然与导入MySQLdb无关 - 否则从一开始你就会得到一个ImportError
,你的代码甚至不会被调用)。
谢谢,我得到了问题的真正原因。问题出在mysql_connector.py中。我无法使用其绝对路径在脚本中定义配置文件。谢谢。 – ChaosDarky
'try'套件发生异常。所以'cursor'没有被成功定义。错误信息应该已经打印在'/ var/log/test.log'中。它说什么? – unutbu
错误发布在上方。它是关于UnboundLocalError:在赋值之前引用的局部变量“游标”。我在模拟时遇到同样的错误,删除导入mysql.connector,然后在shell中执行脚本。 – ChaosDarky
如果你删除'try',''except','finally'行,会在里面放入代码并且只是运行代码“裸”会发生什么?然后你应该在'test.log'中看到真正的原始异常的回溯错误消息。 – unutbu