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)
import os
homedir = os.environ['HOME']
print(homedir)
/home/saltycrane
Get hostname¶
import socket
hostname = socket.gethostname()
print(hostname)
scooby
Comments
if you need long hostname for example hostname -f use:
lhostname = socket.getfqdn()
disqus:3502647674
thanks!
disqus:3583589663