2016-02-05 35 views
2

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

謝謝

+0

'try'套件發生異常。所以'cursor'沒有被成功定義。錯誤信息應該已經打印在'/ var/log/test.log'中。它說什麼? – unutbu

+0

錯誤發佈在上方。它是關於UnboundLocalError:在賦值之前引用的局部變量「遊標」。我在模擬時遇到同樣的錯誤,刪除導入mysql.connector,然後在shell中執行腳本。 – ChaosDarky

+0

如果你刪除'try',''except','finally'行,會在裏面放入代碼並且只是運行代碼「裸」會發生什麼?然後你應該在'test.log'中看到真正的原始異常的回溯錯誤消息。 – unutbu

回答

1

你看了回溯嗎?問題很明顯:在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塊之前定義conncursorNone,這樣你在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,你的代碼甚至不會被調用)。

+0

謝謝,我得到了問題的真正原因。問題出在mysql_connector.py中。我無法使用其絕對路徑在腳本中定義配置文件。謝謝。 – ChaosDarky