How to get the current username in Python
In this article, we will discuss how to get the current username in python.
Method 1: Using OS library
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
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.
Example 3: environ.get() method
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 .
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( )
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() )
Here  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  .