Sunday, October 6, 2024
Google search engine
HomeLanguagesHow to get the current username in Python

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

Python3




# importing os module
import os
 
 
# using getlogin() returning username
os.getlogin()


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




# importing required module
import os
 
# using path.expanduser() getting username
os.path.expanduser('~')


Output :

'C:\\Users\\KRISHNA KARTHIKEYA'

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 .

Python3




# importing os module
import os
 
# using environ.get() method getting
# current username
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




# importing getpass library using import command
# Here gt is a alias name for getpass
# Instead of writing getpass we can use gt
import getpass as gt
 
# using getuser() method , returning current
# username
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




# importing required modules
import os
import pwd
 
# Using getpwuid() and getuid we are
# printing current username
pwd.getpwuid(os.getuid())[0]


Output :

'root'

RELATED ARTICLES

Most Popular

Recent Comments