Getting name of windows computer running python script?

前端 未结 7 1600
耶瑟儿~
耶瑟儿~ 2021-01-30 01:15

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 c

相关标签:
7条回答
  • 2021-01-30 01:46

    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'
    
    0 讨论(0)
  • 2021-01-30 01:47
    import socket
    pc = socket.gethostname()
    print pc
    
    0 讨论(0)
  • 2021-01-30 01:47

    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'
    
    0 讨论(0)
  • 2021-01-30 01:49

    I bet gethostname will work beautifully.

    0 讨论(0)
  • 2021-01-30 01:55

    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 ;)

    0 讨论(0)
  • 2021-01-30 02:05
    import socket
    socket.gethostname()
    
    0 讨论(0)
提交回复
热议问题