Skip to content
Related Articles

Related Articles

How to get the current username in Python

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 23 Jan, 2022

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


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

Output :


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.


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

Output :


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 .


# importing os module
import os
# using environ.get() method getting
# current username

Output :


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 :


# 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

Output :


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  : 


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

Output :


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!