将数组转换为以逗号分隔的连续字符串的脚本

时间:2013-01-02 10:44:17

标签: python

我正在尝试获取存储在LDAP数据库中的所有电子邮件地址的列表,以逗号分隔。

通过简化script,我有:

#!/usr/bin/env python
# encoding: utf-8

# Author:   Zhang Huangbin <zhb _at_ iredmail.org>
# Purpose:  Add enabledService=lib-storage for all mail users.
#           Required by IMAP folder sharing in Dovecot-2.0.
# Date:     2012-05-18

import sys
import ldap

# Note:
#   * bind_dn must have write privilege on LDAP server.
uri = 'ldap://127.0.0.1:389'
basedn = 'o=domains,dc=example,dc=com'
bind_dn = 'cn=Manager,dc=example,dc=com'
bind_pw = 'password'

# Initialize LDAP connection.
print >> sys.stderr, "* Connecting to LDAP server: %s" % uri
conn = ldap.initialize(uri=uri, trace_level=0,)
conn.bind_s(bind_dn, bind_pw)

# Get all mail users.
print >> sys.stderr, "* Get all mail accounts..."
allUsers = conn.search_s(
        basedn,
        ldap.SCOPE_SUBTREE,
        "(objectClass=mailUser)",
        ['mail', 'enabledService'],
        )

total = len(allUsers)
print >> sys.stderr, "* Total %d user(s)." % (total)

# Counter.
count = 1

for user in allUsers:
    (dn, entry) = user
    mail = entry['mail'][0]

    print >> "%s, " % (mail)

    count += 1

# Unbind connection.
conn.unbind()

当我运行时,我收到错误:

  
      
  • 连接到LDAP服务器:ldap://127.0.0.1:389
  •   
  • 获取所有邮件帐户......
  •   
  • 共有64位用户。回溯(最近一次调用最后一次):文件“list_mail_users.py”,第43行,中   打印&gt;&gt; “%s,”%(mail)AttributeError:'str'对象没有属性'write'
  •   

我在支持论坛上问了这个问题,他们建议我使用:ldapsearch而不是?

1 个答案:

答案 0 :(得分:1)

这是你的问题

for user in allUsers:
  (dn, entry) = user
  mail = entry['mail'][0]

  print >> "%s, " % (mail)

  count += 1

您正在尝试打印到“%s”,这是一个字符串,print只能接受具有write属性的对象。我不确定你要做的是什么,但我会期待像print >> sys.stdout, "%s, " %(mail)print >> File "%s, "%mail

这样的东西