首先我使用的是python 2.7。
我想要实现的是将表数据从活动目录查找分离为数组中的“Firstname Lastname”项,稍后我可以将其与不同的数组进行比较,并查看列表中的哪些用户不匹配。
我运行dsquery group domainroot -name groupname | dsget group -members | dsget user -fn -ln
,输出一个列表:
fn ln Peter Brill Cliff Lach Michael Tsu Ashraf Shah Greg Coultas Yi Li Brad Black Kevin Schulte Raymond Masters (Admin) James Rapp Allison Wurst Benjamin Hammel Edgar Cuevas Vlad Dorovic (Admin) Will Wang dsget succeeded
请注意,此列表在每个数据集之前和之后都有空格。
我目前使用的代码:
userarray = []
p = Popen(["cmd.exe"], stdin=PIPE, stdout=PIPE)
p.stdin.write("dsquery group domainroot -name groupname | dsget group -members | dsget user -fn -ln\n")
p.stdin.write("exit\n")
processStdout = p.stdout.read().replace("\r\n", "").strip("")[266:]
cutWhitespace = ' '.join(processStdout.split()).split("dsget")[0]
processSplit = re.findall('[A-Z][^A-Z]*', cutWhitespace)
userarray.append(processSplit)
print userarray
我的问题是,当我在空白区域上拆分并尝试将它们重新分组为“名字姓氏”时,当它到达列表中具有(管理员)的行时,由于存在第三个字段,分组将被抛弃。以下是我的意思的样本:
['Brad ', 'Black ', 'Kevin ', 'Schulte ', 'Raymond ', 'Masters (', 'Admin) ', 'James ', 'Rapp ', 'Allison ', 'Wurst ',
如果您对如何更好或正确地分组,我将不胜感激。谢谢!
答案 0 :(得分:1)
# the whole file.
content = p.stdout.read()
# each line as a single string
lines = content.split()
# lets drop the header and the last line
lines = lines[1:-1]
# Notice how the last name starts at col 19
names = [(line[:19].strip(), line[19:].strip()) for line in lines]
print(names)
=> [('Peter', 'Brill'), ('Cliff', 'Lach'), ('Michael', 'Tsu'), ('Ashraf', 'Shah'), ('Greg', 'Coultas'), ('Yi', 'Li'), ('Brad', 'Black'), ('Kevin', 'Schulte'), ('Raymond', 'Masters (Admin)'), ('James', 'Rapp'), ('Allison', 'Wurst'), ('Benjamin', 'Hammel'), ('Edgar', 'Cuevas'), ('Vlad', 'Dorovic (Admin)'), ('Will', 'Wang')]
现在,如果列大小发生变化,只需在删除标题之前执行index = lines[0].indexof('ln')
并使用它而不是19
答案 1 :(得分:0)
split
有一个maxsplit
参数,所以你可以告诉它只拆分第一个分隔符,所以你可以说:
cutWhitespace = ' '.join(processStdout.split(None,1)).split("dsget")[0]
在你的第六行,告诉它分裂不超过一次。