rainbowbird
11/18/2019 - 1:59 AM

Use Python to get the system hostname

Use Python to get the system hostname

Both of these are pretty portable

import platform
platform.node()

import socket
socket.gethostname()

Any solutions using the HOST or HOSTNAME environment variables are not portable. Even if it works on your system when you run it, it may not work when run in special environments such as cron.

import os, platform; 
os.getenv('HOSTNAME', os.getenv('COMPUTERNAME', platform.node())).split('.')[0]

should be cross-platform and support environment variables if they exist - which permits some user control in exigent circumstances.

Ref

How can I use Python to get the system hostname?