Archive

Posts Tagged ‘hostname’

Figure out the hostname

March 3, 2011 Leave a comment

Problem

What is the hostname of your machine? Under bash:

C:~> hostname
jabba-laptop
C:~> echo $HOSTNAME
jabba-laptop

But how to get it in Python?

Solution

from socket import gethostname

print gethostname()

This tip is from here.

What is it good for?

It can be handy when you develop a script that should run on several machines:

from socket import gethostname

host = gethostname()
if host == "my-laptop":
    BASE_DIR = '/home/jabba/public_html'
elif host == "server":
    BASE_DIR = '/home/our_project/public_html'

This way when you copy your script from one machine to another, you don’t need to modify your constants. It can also help to reduce errors: if you forget to customize your constants, your program will not work as expected…

Categories: python Tags:
Design a site like this with WordPress.com
Get started