2009-12-08 52 views
0

我有一個像下面小編代碼:psycopg2 VS sys.stdin.read()

#!/usr/bin/python 
import psycopg2, sys 

try: 
    conn = psycopg2.connect("dbname='smdr' user='bino'"); 
except: 
    print "I am unable to connect to the database" 
cur = conn.cursor() 
v_num = '1' 
cur.execute("SELECT * from genctr WHERE code = %(num)s", dict(num=v_num)) 
rows = cur.fetchall() 
print "\nShow me the databases:\n" 
ctrnum =0 
for row in rows: 
    print row[0]+","+row[1] 
當我運行它

,我得到

[email protected]:~/mydoc/openerp/smdr$ ./genctr.py 

Show me the databases: 

1,Bahamas 
1,Barbados 
1,Canada 
1,Cayman Islands 
1,United States 
1,Virgin Islands U.S. 

我試圖取代「v_num = '1' 「與 」v_num = sys.stdin.read()「

#!/usr/bin/python 
import psycopg2, sys 

try: 
    conn = psycopg2.connect("dbname='smdr' user='bino'"); 
except: 
    print "I am unable to connect to the database" 
cur = conn.cursor() 
#v_num = '1' 
v_num = sys.stdin.read() 
cur.execute("SELECT * from genctr WHERE code = %(num)s", dict(num=v_num)) 
rows = cur.fetchall() 
print "\nShow me the databases:\n" 
ctrnum =0 
for row in rows: 
    print row[0]+","+row[1] 

但是當我運行它,我只得到了這一點:

[email protected]:~/mydoc/openerp/smdr$ echo 1 |./genctr.py 

Show me the databases: 

請請給我你對如何解決它

真誠

-bino-

回答

1

echo 1是要給 「1個\ n」 來你的程序(即啓蒙「 1「後換行符)。 sys.stdin.read()將返回確切的字符串,然後psycopg2將準備SQL語句爲SELECT * from genctr WHERE code = '1\n'。結果是沒有匹配的結果,所以for循環內的代碼永遠不會執行,這就是爲什麼你沒有看到任何額外的輸出。

嘗試執行echo -n 1來抑制換行符,或者sys.stdin.read().strip()從字符串中刪除任何前導和尾隨空格。如果code字段是一個整數,它可能是一個好主意,把結果的sys.stdin.read()爲int,太像這樣:

int(sys.stdin.read().strip()) 
+0

親愛的扎克·赫希 謝謝你們的啓蒙 它的工作就像一個魅力 真誠 -bino- – 2009-12-08 08:37:50