9

I'm looking for a cross platform solution for getting current login/username in Python.

I was surprised that os.getlogin() is only supported under Unix and even there is not necessarily returning what you would expect.

karel
  • 4,637
  • 41
  • 42
  • 47
bogdan
  • 8,194
  • 10
  • 36
  • 42

2 Answers2

12

getpass.getuser() is your friend.

Amber
  • 477,764
  • 81
  • 611
  • 541
1

Here is what I use:

import os
username = getattr(os, "getlogin", None)
if not username:
    for var in ['USER', 'USERNAME','LOGNAME']:
        if  var in os.environ:
            username = os.environ[var]
print("username: %s" % (username))
sorin
  • 149,293
  • 163
  • 498
  • 754