Getting name of windows computer running python script?

From https://mail.python.org/pipermail/python-list/2006-April/397494.html

import os
os.getenv('COMPUTERNAME')

As Eric Palakovich Carr said you could use these three variants.

I prefer using them together:

def getpcname():
    n1 = platform.node()
    n2 = socket.gethostname()
    n3 = os.environ["COMPUTERNAME"]
    if n1 == n2 == n3:
        return n1
    elif n1 == n2:
        return n1
    elif n1 == n3:
        return n1
    elif n2 == n3:
        return n2
    else:
        raise Exception("Computernames are not equal to each other")

I prefer it when developing cross patform applications to be sure ;)


It turns out there are three options (including the two already answered earlier):

>>> import platform
>>> import socket
>>> import os
>>> platform.node()
'DARK-TOWER'
>>> socket.gethostname()
'DARK-TOWER'
>>> os.environ['COMPUTERNAME']
'DARK-TOWER'

import socket
socket.gethostname()