简体   繁体   English

创建和导入模块-NameError:未定义全局名称'c'

[英]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. 我想创建一个简单的脚本来从sqlite数据库中提取和绘制数据。 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: 每个脚本在同一ipython笔记本中运行时都有效,当我尝试使用以下代码创建模块时,它将失败:

My pulldata.py script: 我的pulldata.py脚本:

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. 您的导入是正确的,但是您在main方法中打开了连接,将其用作模块时不会运行。 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 在方法之外到您的pulldata.py文件顶部,然后将其移动

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

inside your pull_data method. 在您的pull_data方法中。

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 import pulldata由于未定义c变量,因此

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. 最终是错误的,因为导入时pulldata并不是您的主要对象,因此它不会输入main()函数且未定义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. 同样, main()函数中的c是局部变量,因此即使定义了它,也无法从其他函数访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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