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
📄
Using multiple environments AWS CLI and profiles with CDK
📄
Configure log retention and removal policy for Lambda function using AWS CDK in Python
📄
Granting Lambda function permission to access DynamoDB using AWS CDK in Python
📄
Granting S3 permissions to a Lambda function using AWS CDK in Python
📄
How to create a Lambda function in a Custom Docker image using AWS CDK in Python