Home > python > Figure out the hostname

Figure out the hostname


What is the hostname of your machine? Under bash:

C:~> hostname
C:~> echo $HOSTNAME

But how to get it in Python?


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:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: