【发布时间】:2019-11-25 16:43:12
【问题描述】:
所以我正在使用 python 中的套接字侦听器,当我将主机 IP 作为用户输入,而不是作为预定义的字符串时,它无法打开连接并显示下面包含的错误消息。当我将主机 IP 作为预定义变量直接放入代码中时,它可以正常工作。我想这是因为所有用户输入末尾都包含换行符。我想问一下之前是否有人遇到过这个问题,是否有任何方法可以过滤掉用户输入末尾的换行符。
代码:
import socket
target_host = raw_input("Please enter a host IP\n")
target_port = *Some Port*
command = "hostname"
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host, target_port))
错误:
client.connect((target_host, target_port))
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 11001] getaddrinfo failed
【问题讨论】:
-
请
print target_host并发布输出? -
target_host = target_host.strip()将删除字符串两端的任何换行符和空格。附带说明:尽管 Python 2.7 将在 2020 年 1 月正式结束生命周期,但您是否有充分的理由继续使用它? -
感谢您的帮助。我会尝试脱衣舞。使用 2.7 不完全是我的选择
-
Strip 修复了它。谢谢。
标签: python python-2.7 sockets input