What is the correct way to get the base (or short?) Hostname?

Is there an easier / better or more pythonic way to get the base hostname?

base_hostname = socket.gethostname().split(".")[0]

      

As an example, how to get localhost just like below:

>>> socket.gethostname()
'localhost.localdomain'
>>> socket.getfqdn()
'localhost.localdomain'
>>> socket.gethostname().split('.')[0]
'localhost'

      

I ask, because I suspect that there is something like a function os.path

abspath

, basename

, join

, split

, splitext

, etc. for managing hostnames, but I haven't found one yet.

+3


source to share


1 answer


You can make it a little more pythonic by splitting the line just once, at most:

import socket
socket.gethostname().split('.', 1)[0]

      



Also, if for some reason you don't want or cannot use the package socket

, an alternative is to use the package platform

:

import platform
platform.node().split('.', 1)[0]

      

+1


source







All Articles