0

我不想用我的整个代码给人们带来负担,所以我将尝试只获取可以帮助回答我的问题的部分

我需要添加一个日期范围作为我的 python 调用的输入

python query2.py -v --start_date='2013-08-12' --finish_date='2013-08-15' > output.txt

但是,当我尝试将其作为连接字符串添加到查询子例程中的 SQL_QUERY 变量时,我收到此错误:

    SQL_QUERY += """ HAVING sm.created >= '2013-08-12' and sm.created <= '2013-0
8-15' """
UnboundLocalError: local variable 'SQL_QUERY' referenced before assignment
Killed by signal 2.

所以我猜我不能以这种方式添加变量,

SQL_QUERY += " HAVING sm.created >= " + options.db_start + " and sm.created <= " + options.db_finish

有人可以告诉我有什么问题吗?

谢谢

import sys
import os
import time
import optparse
import getpass
import subprocess
from contextlib import contextmanager
import MySQLdb


# TODO: modify this with columns, course_id that make sense for you
SQL_QUERY = """
select au.email, sm.created, sce.created , sm.grade, sm.max_grade
from auth_user au, courseware_studentmodule sm,  student_courseenrollment sce
where sm.student_id = au.id and sm.student_id = sce.id
and sm.course_id = 'MyCourse'
and sm.module_type = 'problem' 
"""

def query():
    """

    SQL_QUERY += " HAVING sm.created >= " + options.db_start + " and sm.created <= " + options.db_finish
    log_info("query = %s" % SQL_QUERY)
    result = None
    conn = None
    try:
        conn = MySQLdb.connect(host='127.0.0.1', 
                port=options.local_port,
                user=options.db_user, 
                passwd=options.db_password, 
                db=options.db_name);
        cur = conn.cursor()
        cur.execute(SQL_QUERY)
        result = cur.fetchall()
    except MySQLdb.Error as e:
        sys.stderr.write("Database error %d: %s\n" % (e.args[0],e.args[1]))
    if conn:
        conn.close()
    return result


def parse_command_line():
    usage = """usage: %prog [options]

 parser.add_option("--start_date", dest="db_start", 
        help="Database host (default=\"%s\"" % DEFAULT_DB_HOST)
    parser.add_option("--finish_date", dest="db_finish", 
        help="Database host (default=\"%s\"" % DEFAULT_DB_HOST)
    global options
    (options, args) = parser.parse_args()
4

1 回答 1

0

query()功能中,您必须首先使用global SQL_QUERY。这里发生的事情是 Python 假定分配给函数内任何位置的任何名称都是该函数的本地名称,除非另有明确说明。如果它只是从一个名称中读取,并且该名称在本地不存在,它将尝试在任何包含范围(例如模块的全局范围)中查找该名称。

于 2013-08-23T08:50:30.297 回答