Get the hostname of a system in python

Posted in python

There are multiple ways to do it. Some are platform dependent.
The best way is probably through socket:

import socket
hostname = socket.gethostname()

Using os.uname won’t work on windows, but if you’re alreadying importing os and just need to support Linux, this is pretty easy. Why bother importing socket when you don’t need it? You could import gethostname from socket rather than the blanket import. But then you whenever you call gethostname it’s not obvious where it’s coming from.

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

There’s also platform:

import platform
hostname = platform.node()

I know this works in Linux, it should work on Windows too.

Posted by admica   @   7 October 2011

Related Posts

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

*

Previous Post
«
Next Post
»
Powered by Wordpress   |   Lunated designed by ZenVerse

Valid XHTML 1.0 Transitional