简体   繁体   English

无法获取主机名和 IP 并输出到文件 Python3

[英]Unable to get Hostname and IP and output to file Python3

I am currently trying to write my first Python3 program.我目前正在尝试编写我的第一个 Python3 程序。 In my program I am calling upon socket to get the IP and Hostname and write it to a file using a function (See code below).在我的程序中,我调用套接字来获取 IP 和主机名并使用函数将其写入文件(参见下面的代码)。 However, whenever I call the function it never outputs the IP or Hostname to the file IP.txt, it only writes the except message.但是,每当我调用该函数时,它都不会将 IP 或主机名输出到文件 IP.txt,它只会写入 except 消息。

def get_Host_name_IP(): 
    try:
        f = open("IP.txt","w+") 
        host_name = socket.gethostname() 
        host_ip = socket.gethostbyname(host_name) 
        f.write("Hostname :  ", host_name)
        f.write("IP : ", host_ip)

    except: 
        f.write("Unable to get Hostname and IP")

write() takes one argument (string), so you need to format your strings properly: write()接受一个参数(字符串),因此您需要正确格式化字符串:

def get_Host_name_IP(): 
    try:
        f = open("IP.txt","w+") 
        host_name = socket.gethostname() 
        host_ip = socket.gethostbyname(host_name) 
        f.write(f"Hostname :  {host_name}\n")
        f.write(f"IP : {host_ip}")
    except: 
        f.write("Unable to get Hostname and IP")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM