Python os.getlogin() method
The os.getlogin()
method returns the name of the user who is currently logged into the controlling terminal/machine. The getlogin()
is a built-in function of the operating system module and comes default with Python.
Syntax
The syntax of os.getlogin()
method is:
os.getlogin()
Parameters
The os.getlogin()
method does not take any parameters.
Return Value
The os.getlogin()
method returns the name of the user who is currently logged into the controlling terminal of the process.
Note: It is better to use getpass.getuser()
method as it checks the environment variables LOGNAME
, USER
, LNAME
, and USERNAME
to find out the current logged-in user and returns the value of the first one, which is set to a non-empty string.
Example 1 - How to get the current logged-in username in Python
As shown below, we can get the current logged-in username in Python using the os.getlogin()
function.
# import os module
import os
# fetch the username who is
# currently loggedin to the system
username= os.getlogin()
# print the username
print(username)
Output
Ram
Example 2 - Fix OSError: [Errno 25] Inappropriate ioctl for device
A controlling terminal allows a user to control the execution of jobs within the session. If the controlling terminal is not present, the os.getlogin() function raises OSError: [Errno 25] Inappropriate ioctl for device error**.**
To solve the issue, we can use an in-built portable Python library called getpass and use the getpass.getuser()
method that helps get the user's login name.
# import getpass module
import getpass
# fetch the username who is currently
# loggedin to the system using getpass.getuser()
username= getpass.getuser()
# print the username
print(username)
Output
Ram
Conclusion
The os.getlogin()
method is a built-in function of the operating system module, mainly used to get the name of the user currently logged in to the process's controlling terminal. It is recommended to use getpass.getuser()
method over os.getlogin()
method.