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}")
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? Open a discussion thread on GitHub.
Related Posts
📄
How to create a Lambda function in a Custom Docker image using AWS CDK in Python
📄
How to create a Lambda function in a ECR Docker image using AWS CDK in Python
📄
Upgrade Python to latest version (3.12) on Ubuntu Linux or WSL2
📄
Run Selenium and Chrome on WSL2 using Python and Selenium webdriver
📄
Add CORS configuration to a S3 bucket using AWS CDK