Get username, hostname and home directory using Python
On this page
For a variety of reason your Python app might want to know the username of the logged in user along with a few other details such as path to their home directory and their systems hostname.
In Python, you can use use getpass library to fetch these.
Get the username
Run the below to get the username
import getpass
username = getpass.getuser()
print(f"Hello {username}")
Output
On Linux you see

This will also work on Windows

Get the path to home directory
import os.path
homedir = os.path.expanduser("~")
print(homedir)
Output
On Linux

And on Windows

Get the hostname
import socket
hostname = socket.gethostname()
print(hostname)
Output
On Linux

And on Windows

Need help?
Start a discussion on GitHub if you’ve got questions or improvements. Open discussions →