python - 如何将空终端输出从服务器发送到客户端?
问题描述
我正在尝试将 linux 命令从客户端发送到服务器并将服务器输出重新发送到客户端。我可以将所有命令发送到服务器,它们在服务器端工作,但是当我发送像“mkdir、rmdir 等”这样的命令时。这些命令在服务器端工作,但客户端无法接收终端输出消息。我认为这是因为实际上还没有输出消息,我的客户端卡住了,我必须重新启动它。
客户端:
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 was given
,您可以为每个响应添加前缀。
像这样的东西:
if data[0:prefix_len]== success_prefix:
print(data[prefix_len:]
elif data[0:prefix_len] == empty_prefix:
print("command had no output")
推荐阅读
- javascript - 每次单击图像时使用 Javascript 将图像更改为新图像
- python - Python解决循环导入而不合并文件
- r - 用 R 替换基于另一列的列中的值
- postman - 如何在邮递员测试中计算数组内的元素
- node.js - at=error code=H10 desc="App crashed" on heroku。我如何才能真正部署?我如何解决问题?谢谢大家
- airflow - 气流:如何在失败后停止下一个 dag 运行
- java - 编写 KStream
> 到 Kafka 主题 - javascript - 使用带有 useEffect 的 usereducer
- c++ - 关于 C++ 中的右值引用
- php - Rest API - GET 请求返回 404 错误,并作为响应 0 与现有 account_id