views:

1053

answers:

5

Basically, I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script.

How would I get that computer name in the python script?

Let's say the script was running on a computer named DARK-TOWER, I'd like to write something like this:

>>> python.library.getComputerName()
'DARK-TOWER'

Is there a standard or third party library I can use?

+2  A: 

I bet gethostname will work beautifully.

Promit
Promit from GameDev? Thanks for the answer :)
Eric Palakovich Carr
The very same. I got enough answers from SO that I thought I should contribute.
Promit
+3  A: 

Since the python scrips are for sure running on a windows system, you should use the Win32 API GetComputerName or GetComputerNameEx

You can get the fully qualified DNS name, or NETBIOS name, or a variety of different things.

import win32api
win32api.GetComputerName()

>>'MYNAME'

Or:

import win32api
WIN32_ComputerNameDnsHostname = 1 
win32api.GetComputerNameEx(WIN32_ComputerNameDnsHostname)

>> u'MYNAME'
Brian R. Bondy
+4  A: 

From http://mail.python.org/pipermail/python-list/2006-April/552293.html

import os
os.getenv('COMPUTERNAME')
oneporter
Thank you everyone for your answers. They all work fine, so I picked the person with the lowest rating.
Eric Palakovich Carr
+2  A: 
import socket
socket.gethostname()
inkedmn
+10  A: 

I know it's in poor taste to post an answer to your own question, but 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'
Eric Palakovich Carr
Answering one's own question may be considered poor taste by some, but it is perfectly fine, as per the FAQ: http://stackoverflow.com/faq
Stephan202
I don't think it's bad at all, since Eric was compiling a few different responses into a single resource, not to mention adding a new one (platform).
nilamo