In this article, we will discuss how to get the current username in python.
getlogin() method of OS library is used to get the current username.
Syntax : os.getlogin( )
In order to use this function we need to import os library first .
Example 1: getlogin() method
Output :
'KRISHNA KARTHIKEYA'
Example 2: os.path.expanduser() method
There is another method available in os library named path.expanduser() method. In this function, we need to pass the Tilde operator within single quotes as an argument.
syntax : os.path.expanduser( )
Note: In this method, we need to pass the tilde operator as an argument.
Python3
import os
os.path.expanduser( '~' )
|
Output :
'C:\\Users\\KRISHNA KARTHIKEYA'
This method is also available in the os module. We need to pass USERNAME as an argument into this method. Let us see the syntax and example .
syntax : os.environ.get( ” USERNAME” )
note : In some cases we need pass USER instead of USERNAME . Most of the cases we pass USERNAME as argument .
Python3
import os
os.environ.get( 'USERNAME' )
|
Output :
'KRISHNA KARTHIKEYA'
Method 2: Using getpass library
In this module, we need to use getuser() method to return the current username. This getuser() method is available in getpass library.
syntax : getpass.getuser( )
Example :
Python3
import getpass as gt
gt.getuser()
|
Output :
'KRISHNA KARTHIKEYA'
Method 3: Using os and pwd modules
pwd module works only with Linux environment. But os works with both Windows and Linux. This means some methods work with only windows and some methods work with only Linux. If we execute this method in Linux we will get output as root. Let us see the syntax and example of getpwuid() method.
syntax : getpwuid( os.getuid() )[0]
Here [0] is like index. Generally this function returns many outputs like system name , password , uid , bash..etc . Here we need username . It is at index 0 . so we are specifying [0] .
Example :
Python3
import os
import pwd
pwd.getpwuid(os.getuid())[ 0 ]
|
Output :
'root'
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
23 Jan, 2022
Like Article
Save Article