Skip to content

Instantly share code, notes, and snippets.

@bryanheinz
Last active August 21, 2020 13:53
Show Gist options
  • Save bryanheinz/03f0a6f93d2dd7b6c3d236e3d6ad2048 to your computer and use it in GitHub Desktop.
Save bryanheinz/03f0a6f93d2dd7b6c3d236e3d6ad2048 to your computer and use it in GitHub Desktop.
Get's the current logged in user in macOS using Python.
#!/usr/local/bin/python3
import subprocess
def termy(cmd):
task = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = task.communicate()
return(out.decode('utf-8'), err)
user, err = termy(
['/usr/bin/stat', '-f', '"%Su"', '/dev/console']
)
user = user.replace('"', '').strip()
if user == 'root':
user, err = termy([
"/usr/bin/defaults", "read",
"/Library/Preferences/com.apple.loginwindow.plist", "lastUserName"
])
user = user.strip()
print(user)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment