当我运行我的python脚本来查询用户时,它会将所有结果打印在一行中(在解释器中)。
我的python脚本中的代码块是:
baseDN = "DC=top,DC=domain,DC=com"
searchScope = ldap.SCOPE_SUBTREE
retrieveAttributes = ["name"]
searchFilter = "cn=*abc*"
try:
ldap_result_id = l.search(baseDN, searchScope, searchFilter,
retrieveAttributes)
result_set = []
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
print result_set
except ldap.LDAPError, e:
print e
以上结果与此类似:
[[('CN=John Doe ,OU=SalesOffices,DC=top,DC=domain,DC=com', {'name': ['John Doe']})], [('CN=Mary Jane,OU=SalesOffices,DC=top,DC=domain,DC=com', {'name': ['Mary Jane']})],
我希望它能垂直打印出来:
[[('CN=John Doe ,OU=SalesOffices,DC=top,DC=domain,DC=com', {'name': ['John Doe']})],
[('CN=Mary Jane,OU=SalesOffices,DC=top,DC=domain,DC=com', {'name': ['Mary Jane']})],
谢谢!
答案 0 :(得分:2)
使用:
而不是print result_set
for x in result_set:
print x
答案 1 :(得分:2)
在python 3或from __future__ import print_function
中,您可以使用sep
关键字和星号表达式:
print(*result_set, sep='\n')
这会将result_set
的元素解压缩为打印的单个参数,并在其间添加换行符。
另外,你可能不应该调用python列表对象result_set
,因为set是另一种内置集合类型。
完整示例(添加ldap服务器并基于):
# __future__ imports have to be the very first imports
from __future__ import print_function
import ldap
host = 'ldap://...'
baseDN = '...'
searchScope = ldap.SCOPE_SUBTREE
retrieveAttributes = ['mail']
searchFilter = 'uid=*'
l = ldap.initialize(host)
l.simple_bind()
try:
ldap_result_id = l.search(
baseDN, searchScope, searchFilter, retrieveAttributes
)
ldap_results = []
# use a bool, be explicit!
while True:
result_type, result_data = l.result(ldap_result_id, 0)
if not result_data:
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
ldap_results.append(result_data)
print(*ldap_results, sep='\n')
except ldap.LDAPError as e:
print(e)
答案 2 :(得分:1)
使用pprint
模块保留所有列表括号:
from pprint import pprint
baseDN = "DC=top,DC=domain,DC=com"
searchScope = ldap.SCOPE_SUBTREE
...
pprint(result_set, width=120)
输出:
[[('CN=John Doe ,OU=SalesOffices,DC=top,DC=domain,DC=com', {'name': ['John Doe']})],
[('CN=Mary Jane,OU=SalesOffices,DC=top,DC=domain,DC=com', {'name': ['Mary Jane']})]]
默认pprint
尝试打印到80列:
pprint(result_set)
输出:
[[('CN=John Doe ,OU=SalesOffices,DC=top,DC=domain,DC=com',
{'name': ['John Doe']})],
[('CN=Mary Jane,OU=SalesOffices,DC=top,DC=domain,DC=com',
{'name': ['Mary Jane']})]]