2012-08-02 52 views
0

我寫一個小python腳本是這樣的:Python2.7 - SQLITE3 - 2個輸入

#!/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循環。

我在哪裏做錯誤?請指導我通過......

回答

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

0

sys.argv的第一個元素是腳本的名稱,所以你可能真的想爲你的if語句如下:

if len(argv) == 3: 
    na = argv[1] 
    ha = argv[2] 
+0

但是,如果我理解正確,'len(argv)'不能超出'2'?或 編輯: 不,我錯了! – user1524529 2012-08-02 22:10:01