How to get the current username in Python

Published on Aug. 22, 2023, 12:15 p.m.

To get the current username in Python, you can use the getpass module or the os module. Here are two ways to do it:

Using the getpass module:

import getpass

username = getpass.getuser()
print(username)

The getuser() function in the getpass module returns the login name of the current user. You can assign the return value of this function to a variable (in this case, username) and print it to the console.

Using the os module:

import os

username = os.getlogin()
print(username)

The getlogin() function in the os module returns the login name of the user currently logged in on the controlling terminal of the process. You can assign the return value of this function to a variable (in this case, username) and print it to the console.

Both methods should give you the same result, which is the username of the current user. Choose the method that best fits your use case.

Tags: