Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Python by (580 points)

Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like os.getuid:

 

>>> os.getuid()

76

>>> os.getusername()

'login name'

I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The pwd module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.

1 Answer

0 votes
by (10.9k points)

@aghosh578, You can use the getpass.getuser() function from the getpass module in Python.

getpass.getuser() function returns the username or the “login name” of the user. This function first checks all the Environment variables in the given order LOGNAME, USER, LNAME, USERNAME and then it returns the value of the first non-empty string. It is available in both windows and Linux.

Ex-

import getpass

getpass.getuser()

'login name'

For more information, kindly refer to our Python course. 

Browse Categories

...