Python – How to get Windows user’s full name in python

pythonwinapiwindows

I'm trying to get the user's full name. Not the login name, but the full name that shows up on the upper right side of the start menu in Windows 7. It might only show up as the full name in an active directory setting.

os.environ['USERNAME']
win32api.GetUserName()

These both return the login name. How do I get the user's full name?

Best Answer

A bit of googling gives me this link

and this code:

import ctypes
 
def get_display_name():
    GetUserNameEx = ctypes.windll.secur32.GetUserNameExW
    NameDisplay = 3
 
    size = ctypes.pointer(ctypes.c_ulong(0))
    GetUserNameEx(NameDisplay, None, size)
 
    nameBuffer = ctypes.create_unicode_buffer(size.contents.value)
    GetUserNameEx(NameDisplay, nameBuffer, size)
    return nameBuffer.value

Tested and works on Windows XP


As noted by OP in comment here, pywin32 wraps this same API call into a simpler function:

win32api.GetUserName(3)

GetUserName pointing to ctypes.windll.secur32.GetUserNameExW, and 3 being the same 3 as the constant from ctypes