How can I use Python to get the system hostname?

Use socket and its gethostname() functionality. This will get the hostname of the computer where the Python interpreter is running:

import socket
print(socket.gethostname())

You will probably load the os module anyway, so another suggestion would be:

import os
myhost = os.uname()[1]

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.


What about :

import platform

h = platform.uname()[1]

Actually you may want to have a look to all the result in platform.uname()