Get username, hostname and home directory using Python

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}")


On Linux you see python find username linux

This will also work on Windows python find username windows

Get the path to home directory

import os.path

homedir = os.path.expanduser("~")


On Linux python find homedir linux

And on Windows python find homedir windows

Get the hostname

import socket
hostname = socket.gethostname()


On Linux python find hostname linux

And on Windows python find hostname windows

Need Help? Open a discussion thread on GitHub.

Related Posts