我有一些python脚本的代码部分我必须查询用户的ldap属性:
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 :(得分: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