当我尝试从客户端向服务器发送带引号的字符串时,它可以工作。但是,当我尝试将存储用户输入的变量发送到服务器时,事实并非如此。有人知道为什么吗?
服务器文件
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind( ("0.0.0.0", 1234) )
buff, addr = s.recvfrom(100)
print buff, addr
client_file
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
nume_user = input()
# s.sendto( nume_user, ("127.0.0.1", 1234) ) # this does not work
s.sendto("john", ("127.0.0.1", 1234) ) # this works
buff, addr = s.recvfrom(100)
print buff
这是我遇到的错误(Ubuntu 18.04 LTS)
Traceback (most recent call last:
File "c4-1.py", line 5, in <module>
nume_user = input()
File "<string>", line 1, in <module>
NameError: name 'ionut' is not defined
答案 0 :(得分:1)
input([提示])
等效于eval(raw_input(prompt))。
因此它将读取您输入的字符串(在这种情况下为ionut
),然后进行评估。由于ionut
不是声明的变量或其他有效的Python语句,因此它将引发显示的错误。
也来自文档:
考虑将raw_input()函数用于用户的常规输入。
这是您应该使用的,然后您没有收到错误。
除了考虑使用Python3代替当前使用的Python2。 Python2已寿终正寝,Python3中的input
函数似乎更像您期望的那样-请参见this documentation。