Skip to content

Instantly share code, notes, and snippets.

@carlashley
Last active August 25, 2021 04:56
Show Gist options
  • Save carlashley/5b2440fdd20adba111feb9eaeb68a5d6 to your computer and use it in GitHub Desktop.
Save carlashley/5b2440fdd20adba111feb9eaeb68a5d6 to your computer and use it in GitHub Desktop.
Returns a named tuple containing information about current logged in user.
#!/usr/bin/env python3
"""Current user logged into macOS, shamelessly stealing macmule's get current
logged in user from https://macmule.com/2014/11/19/how-to-get-the-currently-logged-in-user-in-a-more-apple-approved-way/"""
import pwd
import sys
from collections import namedtuple
try:
from SystemConfiguration import SCDynamicStoreCopyConsoleUser
except ImportError:
print('pip install pyobjc>=7.3', file=sys.stderr)
sys.exit(1)
def current_user():
"""Current user logged into macOS"""
result = None
CurrentUser = namedtuple('CurrentUser', ['username',
'uid',
'gid',
'home',
'shell'])
user = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])
if user:
pwddb = pwd.getpwnam(user[0])
result = CurrentUser(username=user[0],
uid=user[1],
gid=user[2],
home=pwddb.pw_dir,
shell=pwddb.pw_shell)
return result
def main():
"""main"""
print(current_user())
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment