Get Username From OS in Python

Get Username From OS in Python

This article introduces several methods to get the username from OS in Python.

Get Username From OS in Python

When we are working with an application, sometimes we need to verify the operating system user or where we need to get the user of the operating system.

In this tutorial, we will learn about different ways to get the current user of the operating system using Python.

The first method is by using the OS module in Python. First of all, we will import the OS module, and then we will use the getlogin() method to get the logged-in user’s username from the operating system, as shown below.

# python
import os

user = os.getlogin()
print(user)

If we run the above code, the output is below.

get username from OS in python

The above example shows that when the program runs, the output will be the current username of the OS.

If somehow we cannot get the username from the above code. There is another turnaround to get the username.

We will use expanduser from the module os.path in this method. After that, we will get the user’s path, and from the path, we will get the username of the current user, as shown below.

# python
import os

userhome = os.path.expanduser('~')

print("Username: " + os.path.split(userhome)[-1])

If we run the above code, the output is below.

get username from directory in python

The above example shows that we can easily get a username with simple and easy methods.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn