import socket import commands def get_ip(): hostname = socket.gethostname() #print(hostname) hostip = "127.0.0.1" try: hostip = socket.gethostbyname(hostname) # 这个在linux 无法执行, 会走下面的cmd 来获取ip , 但是在windows上这个命令执行,可以获取地址 #print(hostip) return hostip except Exception,ex: # 这个ex 在windows 上会报错 print(ex) if "127.0.0.1" in hostip or not hostip: try: cmd = "ifconfig|grep -v '127.0.0.1'|awk '{print $2}'|grep -oP '(\d+.\d+.\d+.\d+)'|head -1" (status,output) = commands.getstatusoutput(cmd) except Exception,ex: print(ex) return hostip if output and ' ' not in output: local_ip = output return local_ip return hostip hostip = get_ip() print(hostip)