tags:

views:

199

answers:

1

Dear all I have small code like below :

#!/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]

when i run it, i got

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.

I try to replace "v_num = '1' " with "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]

But when I run it , I only got this :

bino@erp:~/mydoc/openerp/smdr$ echo 1 |./genctr.py 

Show me the databases:

Kindly please give me your enlightment on how to fix it

Sincerely

-bino-

+1  A: 

echo 1 is going to give "1\n" to your program (that is, "1" with a newline character afterward). sys.stdin.read() is going to return that exact string, and then psycopg2 is going to prepare the SQL statement as SELECT * from genctr WHERE code = '1\n'. The result is going to be no matching results, so the code inside the for loop will never execute, which is why you don't see any extra output.

Try doing either echo -n 1 to suppress the newline, or sys.stdin.read().strip() to remove any leading and trailing whitespace from the string. If the code field is an integer, it might be a good idea to cast the result of sys.stdin.read() to an int, too, like so:

int(sys.stdin.read().strip())
Zach Hirsch
Dear Zach HirschThankyou for your enlightmentIt work like a charmSincerely-bino-
Bino Oetomo