0
我是Python的新手,使用Python 2.7。我從命令行傳入一個字符串列表,並使用該字符串列表運行兩個不同的查詢。該列表包含4個有效且在第一個查詢中返回的ID。最後兩個ID無效。我需要將兩個結果都打印到一個文件中。查詢沒有結果時Python返回列表
我運行的查詢爲:
python empdetails.py -i "'ADM10','TMC34','LAB57','WSD44','GM22','AD32'" -o (file_location)
import os
import sys,getopt
from impala.dbapi import connect
def main(argv):
input = ''
output = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["input=","output"])
except getopt.GetOptError:
print 'Usage append.py -i <input> -o <output>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'Usage append.py -i <input> -o <output>'
sys.exit()
elif opt in ("-i", "--input"):
input = arg
elif opt in ("-o", "--output"):
output = arg
print input
conn = connect(host='hostname', port=port_number, auth_mechanism='GSSAPI', kerberos_service_name='impala', use_ssl=True)
cursor = conn.cursor()
sql = ('select empcode from empinfo where empcode in (select ecode from emptrav_det where ecode in({}))'.format(input))
cursor.execute (sql)
duplicate = cursor.fetchall()
sql =('select ecode from emptrav_det where exp_c in({})'.format(input))
print sql
cursor.execute (sql)
new = cursor.fetchall()
if duplicate !=0:
with open('output', 'a') as f:
for emp in duplicate:
f.write(str(emp[0]) + " " + ("Traveled\n"))
if new ==0:
with open('output', 'a') as f:
for emp in new:
f.write(str(emp[0]) + " " + ("Invalid ID\n"))
conn.close()
if __name__ == '__main__':
main(sys.argv[1:])
試過這種方式,但沒有得到輸出無效,我也將需要打印的無效 – Venkat
然後寫'input'到您的文件的ID。關鍵是要理解邏輯和你在做什麼錯誤。 'input'是一個不好的變量名btw;它會隱藏內置的Python –