处理命令行参数时的NameError

时间:2012-07-24 20:11:20

标签: python

我正在使用sqlite3尝试一些python测试脚本。

这是我写的脚本

#!/usr/bin/env python

from sqlite3 import dbapi2 as sqlite
from sys import argv,exit

db_name = "filenames.db"

def define_db():
    try:
        conn = sqlite.connect(db_name)
    except IOError as e:
        print "problem while creating/connecting the db:",e.args[0]
        exit(1)

    return conn

def write_db(conn,cursor,fni):
    conn.execute("CREATE TABLE IF NOT EXISTS file (filenames TEXT UNIQUE)")
    query = "INSERT OR REPLACE INTO file VALUES($filenames)"

    cursor.execute(query,[fni])
    cursor.close()  
    conn.commit()
    conn.close()
    print fni,"should now be in the db" 
    exit(0)

if __name__ == "__main__":
    if len(argv) == 2:
        etag = argv[1]
    else:
        print "no argument given - stopping now"
        exit(1)

    conn = define_db()
    cursor = conn.cursor()
    write_db(conn,cursor,fni)

我一直收到此错误,但无法解决。

Traceback (most recent call last):
  File "blah.py", line 37, in <module>
    write_db(conn,cursor,fni)
NameError: name 'fni' is not defined

知道问题是什么。

此时我使用的是python 2.7.3

3 个答案:

答案 0 :(得分:2)

脚本的最后一行是指未定义的名称fni

答案 1 :(得分:0)

您尚未定义变量“fni”,但您正在使用它。

答案 2 :(得分:0)

pyflakespylint这样的静态分析工具可以用来捕捉这样的愚蠢错误

如果你在一个函数中写了大部分代码(所以它不假设blub是一个全局变量,它不会让pyflakes / pylint抱怨):

def main():
    if len(argv) == 2:
        blub = argv[1]
    else:
        print "no argument given - stopping now"
        exit(1)

    conn = define_db()
    cursor = conn.cursor()
    write_db(conn,cursor,fni)

if __name__ == "__main__":
    main()

...然后你会得到一对错误,它们指出了错误是什么(你将参数存储在blub中,但试图用fni访问它):

$ pip install pyflakes
$ pyflakes example.py
example.py:30: local variable 'blub' is assigned to but never used
example.py:37: undefined name 'fni'