简体   繁体   中英

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!!

Your import is correct, but you open the connection in the method main , which you don't run when you use it as a module. Why don't you move these

import matplotlib.pyplot as plt
import datetime
import sqlite3 

outside the method to the top of your pulldata.py file, then move this

c = sqlite3.connect('Test_db19.db')
c.connect()

inside your pull_data method.

Everything under

if __name__ == "__main__":

will not be run if you import the file. This part will only run if, in this case, you do

python pulldata.py

When you import pulldata your c variable doesn't get defined since

if __name__ == "__main__" 

ends up being false because pulldata isn't your main when you import it so it doesn't enter your main() function and doesnt define c. Also the c in your main() function is a local variable so you can't access it from another function even if it was defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM