Python (Scripting) - Return users group using os.getgroups

by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
os.getgroups() can be used to get the username of the user running a Python script.
#!/usr/bin/python3
import os
print(f"group IDs = {os.getgroups()}")
Which should return something like this.
group IDs = [100, 2001]
Or like this, to loop through the group IDs.
#!/usr/bin/python3
import os
group_ids = os.getgroups()
for group_id in group_ids:
print(f"group ID = {group_id}")
Which should return something like this.
group ID = 100
group ID = 2001
Taking this a step further, grp and getgrgid and gr_name can be used to return the group name.
#!/usr/bin/python3
import grp
import os
group_ids = os.getgroups()
for group_id in group_ids:
print(f"group ID = {group_id}")
print(f"group name = {grp.getgrgid(group_id).gr_name}")
Which should return something like this.
group ID = 100
group name = users
group ID = 2001
group name = mygroup
Or like this, as a one liner, to create a list that contains the group names.
#!/usr/bin/python
import grp
import os
group_names = [grp.getgrgid(group_id).gr_name for group_id in os.getgroups()]
Did you find this article helpful?
If so, consider buying me a coffee over at