我的代码如下:
#!/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]
当我运行它时,我得到了
bino@erp:~/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 = sys.stdin.read()”替换“v_num ='1'”
#!/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]
但是当我运行它时,我才得到它:
bino@erp:~/mydoc/openerp/smdr$ echo 1 |./genctr.py
Show me the databases:
请告诉我你如何解决它的启示
此致
-bino -
答案 0 :(得分: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())