mardi 3 mai 2016

Creating and importing a module - NameError: global name 'c' is not defined

I wanted to create a simple script to pull and plot data from a sqlite database. However, when I import the module it doesn't like what I did. Can anyone direct me as to what I am doing wrong?

Each script works when run in the same ipython notebook, when I try to creat a module with the code below, it fails:

My pulldata.py script:

def main()
    import matplotlib.pyplot as plt
    import datetime
    import sqlite3 
    c = sqlite3.connect('Test_db19.db')
    c.connect()

def pull_data(table1, field1):


    x_axis = []
    y_axis = []
    dates = [] 

    for row in c.execute('SELECT date, {fn} FROM {tn} ORDER BY date'.format(tn=table1, fn=field1)):
        y_axis.append(row[1])
        dates.append(row[0])

    for date in dates:

        date1 = datetime.datetime.strptime(date, "%m/%Y").date()
        x_axis.append(date1)

    plt.plot(x_axis,y_axis, marker = "o")
    plt.xlabel('Date')
    plt.ylabel(field1)
    plt.title(table1)

    plt.xticks(rotation=70)

    plt.legend()
    plt.show()


if __name__ == "__main__":
    main()

Trying to import it:

 import pulldata as pd
 pd.pull_data(table_name, column_name)

I am getting:

 "NameError: global name 'c' is not defined"

Any advice/help would be greatly appreciated!!

Aucun commentaire:

Enregistrer un commentaire