Python 为什么我总是获取无法识别的命令输出
这是主机可以输入的命令Python 为什么我总是获取无法识别的命令输出,python,python-3.8,Python,Python 3.8,这是主机可以输入的命令 elif 'command' == "custom_dir": conn.send(command.encode()) print("") user_input = input(str("Custom Dir : ")) conn.send(user_input.encode()) print("")
elif 'command' == "custom_dir":
conn.send(command.encode())
print("")
user_input = input(str("Custom Dir : "))
conn.send(user_input.encode())
print("")
print("Command has been sent")
print("")
files = conn.recv(5000)
files = files.decode()
print("Custom Dir Result : ", files)
else:
print("")
print("Command not recognized")
这是收到此命令的人(有时会崩溃)
即使我将“command”更改为command,我仍然会得到相同的输出
“command”是字符串文本。字符串'command'
永远不会等于字符串“custom_dir”
。这与5==6
是一样的-它们永远不会相等
您的意思是指一个名为command
的变量吗?在这种情况下,写下:
elif command == "custom_dir":
TCP是一种不知道消息边界的流协议。您假设conn.send(user\u input.encode())
将被user\u input=s.recv(5000)
完全接收,但事实并非如此。它可能只接收,比如说“Docu”而不是“Documents”,或者更糟糕的是,只接收部分编码消息。有很多方法可以解决这个问题,还有许多现有的协议,如XMLRPC、HTTP REST、zeromq等。。这提供了解决方案
一个选项是使用b“\n”作为命令终止符(并且不允许在命令中使用“\n”)。使用UTF-8,您可以扫描此终止符并分块接收。在发送端,只需使用sendall(command.encode('utf-8'+b'\n')
,recv端有一个例程,在使用前将传入的数据拆分到b'\n'上。这只是一种方法,但示例很好,所以
类RecvMsgUtf8:
def __init__(self, skt, recvsize=5000):
self.skt = skt
self.recvsize = recvsize
self.closed = False
self.commands = []
self.buf = []
def recvmsg(self):
while True:
# process pending commands
if self.commands:
command = self.commands.pop(0)
if not command:
self.closed = True
else:
return command.decode("utf-8")
if self.closed:
return ""
# get new commands
buf = self.skt.recv(self.recvsize)
if not buf:
self.commands.append(b"")
continue # back to command process
# split raw buffer into commands
self.buf += buf
while self.buf:
cmd_end = self.buf.find(b"\n")
if cmd_end == -1:
continue # process commands and wait for data
self.commands.append(self.buf[:cmd_end])
self.buf = self.buf[cmd_end:]
要使用它,在你的接收器代码的更高位置,你会这样做
receiver = RecvMsgUtf8(s, 5000)
在您当前的代码中,不要使用s.recv,而是
receiver.recvmsg()
“总是”和“有时”是互斥的。这是什么意思?你说的“崩溃”是什么意思?这里需要更多(准确/明确)的细节,伙计。这句话elif'command'==“custom\u dir”
不起作用。word命令
永远不会等于word自定义目录
我仍然得到相同的结果output@Grogu,打印什么(命令)
在整个if
语句输出之前?它将输出发送到第二个脚本我的意思是,在if
语句之前command
的值是多少?command=s.recv(1024)command=command.decode()在我的情况下,我做什么:command.recvmsg(s,5000)不,在本例中,recv缓冲区大小是在创建对象时确定的,并且任何给定的命令都是以块的形式拼凑在一起的。因此,例如,您可以接收兆字节。由于缓冲数据的累积,这对于大负载是无效的。如果您的数据有换行符(例如,您正在接收文本文件)然后,需要另外一个步骤将换行符转义到其他字符序列。
receiver.recvmsg()