I am trying to create a flattened list of all users that belong to a linux group.
The structure returning from grp.getgrall()
is:
[
grp.struct_group(
gr_name='plugdev',
gr_passwd='x',
gr_gid=46,
gr_mem=[
'rolf',
'public'
])
]
where the members of the group are in the form of a list in gr_mem=[]
I can use the following:
import grp
plugdev_members = []
for group in grp.getgrall():
if "plugdev" in group.gr_name:
for user in group.gr_mem:
plugdev_members.append(user)
which returns a flat list:
['rolf','public']
Using list comprehension:
plugdev_members = [
mem for mem in [
m.gr_mem for m in grp.getgrall()
if "plugdev" in m.gr_name
]
]
or
plugdev_members = [
m.gr_mem for m in grp.getgrall()
if "plugdev" in m.gr_name
]
I get a list within a list:
[['rolf', 'public']]
I'm sure that there must be a way to return a flattened list using list comprehension, I'm just not seeing it. I know that I need a second loop within the first, as per the first example but I'm just not getting it right.
Any tips would be appreciated