2017-04-19 45 views
0

創建方法,我有一個python腳本我要查詢用戶的LDAP屬性的代碼部分的該位:從現有Python代碼

try: 
    ldap_result_id = l.search(baseDN, searchScope, get_searchFilter(adname), 
retrieveAttributes) 
    result_set = [] 
    while 1: 
     result_type, result_data = l.result(ldap_result_id, 0) 
     if (result_data == []): 
      break 
     else: 
      ## you could do whatever you want with the individual entry 
      ## The appending to list is just for illustration. 
      if result_type == ldap.RES_SEARCH_ENTRY: 
       result_set.append(result_data) 
    for x in result_set: 
     print x 
except ldap.LDAPError, e: 
    print e 
    print ldap.LDAPError 

如何清潔這件事,使之成爲一個可重複使用的功能(或者說Method是更合適的術語)?

+0

既然你不打算生產類,「功能」是更合適的和唯一正確的術語。 – DyZ

+0

@DYZ如果我開始使用**類**,那麼它會成爲一個**方法**? – Xtos

+0

僅當它是班級的一部分時。 – DyZ

回答

1

確定可以更改的變量並將這些參數設置爲函數。離開印刷和異常處理功能,除非你可以做一些合理的不同之處外:

def fn(baseDN, searchScope, adname, retrieveAttributes): 
    ldap_result_id = l.search(baseDN, searchScope, get_searchFilter(adname), 
retrieveAttributes) 
    result_set = [] 
    while 1: 
     result_type, result_data = l.result(ldap_result_id, 0) 
     if (result_data == []): 
      break 
     else: 
      ## you could do whatever you want with the individual entry 
      ## The appending to list is just for illustration. 
      if result_type == ldap.RES_SEARCH_ENTRY: 
       result_set.append(result_data) 
    return result_set 

baseDN = ??? 
searchScope = ??? 
adname = ??? 
retrieveAttributes = ??? 
try: 
    for x in fn(baseDN, searchScope, adname, retrieveAttributes): 
     print x 
except ldap.LDAPError, e: 
    print e 
    print ldap.LDAPError 
+0

我假設'baseDN = ???,searchScope = ???,adname = ???和retrieveAttributes = ???'應該從腳本中省略? – Xtos

+0

這些是需要提供的變量,例如,用戶輸入,從數據存儲中讀取,由另一個應用程序傳遞等等。 – AChampion

+0

gotcha!是的,我已經在另一節中提供了我的python腳本!你的解決方案非常好用! – Xtos