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
  • 5,489
  • 46
  • 45
  • 50
bogdan
  • 9,056
  • 10
  • 37
  • 42

2 Answers2

11

getpass.getuser() is your friend.

Amber
  • 507,862
  • 82
  • 626
  • 550
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
  • 161,544
  • 178
  • 535
  • 806