在python上将变量从一个脚本传递到另一个脚本

时间:2014-12-17 02:45:02

标签: python

我有两个脚本,qyeryfunction.py和generatecharts.py。我想从queryfunction获取week_number变量的结果,并将它们放在generate weeks中的generatecharts.py中。我怎么能这样做?

#queryfunction.py
import MySQLdb

try:
    db = MySQLdb.connect("localhost","myusr","mypass","mydb")
except MySQLdb.DatabaseError:
    print 'Cant connect to database, check if MySQL service is running'

class WeekQuery:
    def __init__(self, name):
        self.name = name

    def query(self):
        try:
            cursor = db.cursor()
            cursor.callproc(self)
            results = cursor.fetchall()
            week_number = [i[0] for i in cursor.description]
        except MySQLdb.ProgrammingError:
            print 'Data unavailable'
            cursor.close()
        return results

#generatecharts.py
from queryfunction import WeekQuery, query

#class GenerateCharts():

n = WeekQuery('my_first_query')
g = WeekQuery('my_second_query')

first_data = query(n.name)
second_data = query(g.name)
weeks = ???

1 个答案:

答案 0 :(得分:3)

您也可以从week_number中的query函数返回queryfunction.py变量:

return (results, week_number)

您必须稍微更改generatecharts.py以接受元组作为返回值。这会将results分配给first_dataweek_number分配给weeks

first_data, weeks = query(n.name)