SaltyCrane Blog — Notes on JavaScript and web development

How to get username, home directory, and hostname with Python

Get username

Use getpass.getuser

import getpass
username = getpass.getuser()
print(username)
saltycrane

Get home directory

Use os.path.expanduser (h/t Bachsau) or os.environ

import os.path
homedir = os.path.expanduser("~")
print(homedir)
or
import os
homedir = os.environ['HOME']
print(homedir)
/home/saltycrane

Get hostname

Use socket.gethostname

import socket
hostname = socket.gethostname()
print(hostname)
scooby

Comments


#1 YOgly commented on :

if you need long hostname for example hostname -f use:
lhostname = socket.getfqdn()

disqus:3502647674