2017-07-13 25 views
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:]) 

回答

0

的問題是在這裏:

所有的
if new == 0: 
    with open('output', 'a') as f: 
     for emp in new: 
      f.write(str(emp[0]) + " " + ("Invalid ID\n")) 

首先,new將是一個空listtuple。要檢查的是,你不能做if new == 0 ..你必須做一些事情,如:

if not new: 

第二個問題是你的邏輯:

你迭代new,用於檢查if new == 0塊內部。你期望如何工作? (從我猜測的代碼中複製粘貼過多)。做到這一點,而不是:

if not new: 
    with open('output', 'a') as f: 
     f.write("Invalid ID\n") 
+0

試過這種方式,但沒有得到輸出無效,我也將需要打印的無效 – Venkat

+0

然後寫'input'到您的文件的ID。關鍵是要理解邏輯和你在做什麼錯誤。 'input'是一個不好的變量名btw;它會隱藏內置的Python –