我正在写一个像这样的小python脚本:
#!/usr/bin/env python
from sqlite3 import dbapi2 as sqlite
from sys import argv,exit
db_name = "hashez.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,na,ha):
conn.execute("CREATE TABLE IF NOT EXISTS user (name TEXT UNIQUE, hash TEXT UNIQUE)")
query = "INSERT OR REPLACE INTO user VALUES($name,$hash)"
cursor.execute(query,[na],[ha])
cursor.close()
conn.commit()
conn.close()
exit(0)
if __name__ == "__main__":
if len(argv) == 2:
na,ha = argv[1]
#ha = argv[2]
else:
print "no argument given - stopping now"
exit(1)
conn = define_db()
cursor = conn.cursor()
write_db(conn,cursor,na,ha)
当我尝试接受一个输入时,我没有问题
python user.py blah
但是当我尝试使用多个时,它会进入else循环。
我在哪里做错误?请引导我通过...
答案 0 :(得分:1)
您收到此错误,因为第一个参数实际上是文件名。
一个简单的测试文件显示了它的工作原理:
[~]$ cat test.py
from sys import argv
if __name__ == '__main__':
print argv
print len(argv)
[~]$ python test.py one two
['test.py', 'one', 'two']
3
[~]$ python test.py one
['test.py', 'one']
2
您还应修复SQL /查询
query = "INSERT OR REPLACE INTO user VALUES(?,?)"
cursor.execute(query,[na,ha])
conn.commit()
请参阅sqlite api docs。
答案 1 :(得分:0)
sys.argv
中的第一个元素是脚本的名称,因此您可能真的想要if语句的以下内容:
if len(argv) == 3:
na = argv[1]
ha = argv[2]