Python 如何将空终端输出从服务器发送到客户端?
我正在尝试将一个sendlinux命令从客户端发送到服务器,并将服务器输出重新发送到客户端。我可以将所有命令发送到服务器,它们在服务器端工作,但当我发送mkdir、rmdir等命令时,这些命令在服务器端工作,但客户端无法接收终端输出消息。我想这是因为实际上还没有输出消息,我的客户端被卡住了,我必须重新启动它 客户端:Python 如何将空终端输出从服务器发送到客户端?,python,linux,client-server,Python,Linux,Client Server,我正在尝试将一个sendlinux命令从客户端发送到服务器,并将服务器输出重新发送到客户端。我可以将所有命令发送到服务器,它们在服务器端工作,但当我发送mkdir、rmdir等命令时,这些命令在服务器端工作,但客户端无法接收终端输出消息。我想这是因为实际上还没有输出消息,我的客户端被卡住了,我必须重新启动它 客户端: while True: # message sent to server s.send(message.encode('ascii'))
while True:
# message sent to server
s.send(message.encode('ascii'))
# messaga received from server
data = s.recv(1024)
# print the received message
# here it would be a reverse of sent message
print('Received from the server :',str(data.decode('ascii')))
# ask the client whether he wants to continue
ans = input('\nDo you want to continue(y/n) :')
if ans == 'y':
message = input("enter message")
continue
else:
break
# close the connection
s.close()
服务器端:
while True:
# data received from client
data = c.recv(1024)
if not data:
print('Bye')
break
try:
data_o = subprocess.check_output(data, shell=True)
except subprocess.CalledProcessError as e:
c.send(b'failed\n')
print(e.output)
#data_o = subprocess.Popen(["echo", data], stdout=subprocess.PIPE)
print(type(data_o))
c.send(data_o)
示例输出:
感谢您的帮助因为输出是长度为0的字节对象,所以根本不发送任何内容,但您的客户端一直在等待答复。一个简单的解决方案是只发送一个字符串,就像没有给出输出一样。 为了防止在发送echo no output命令时出现混淆,可以为每个响应添加前缀 大概是这样的:
if data[0:prefix_len]== success_prefix:
print(data[prefix_len:]
elif data[0:prefix_len] == empty_prefix:
print("command had no output")
我发现了一个类似的问题。请检查这篇文章