【问题标题】:ping results in websocket python在 websocket python 中 ping 结果
【发布时间】:2022-01-14 19:42:21
【问题描述】:

我正在尝试在烧瓶 python 后端测试执行脚本,并将实时终端结果作为 websocket 或 http 请求发送到前端。

我尝试使用flask_sock 以及一个运行不断 ping 谷歌的 powershell 脚本的函数。我试图在前端查看结果,但它只给了我处理结果,而不是实时结果。

烧瓶袜代码:

from flask_sock import Sock
sock = Sock(app)
@sock.route('/echo')
def echo(ws):
    while True:
        data = ws.receive()
        ws.send(subprocess.run(["powershell", "pingtest.ps1"]))

html javascript 代码:

function WebSocketTest() {
               var ws = new WebSocket("ws://localhost:5000/echo");
               
               ws.onopen = function() {
                   ws.send("test")
               };

               ws.onmessage = function (evt) { 
                  var received_msg = evt.data;
                  alert(received_msg);
               };
                
               ws.onclose = function() { 
               };
         }
         WebSocketTest()

我期待:

Pinging www.google.com [216.58.193.196] with 32 bytes of data:
Reply from 216.58.193.196: bytes=32 time=14ms TTL=115
Reply from 216.58.193.196: bytes=32 time=16ms TTL=115
Reply from 216.58.193.196: bytes=32 time=18ms TTL=115
Reply from 216.58.193.196: bytes=32 time=20ms TTL=115
Reply from 216.58.193.196: bytes=32 time=11ms TTL=115

但我得到了:

CompletedProcess(args=['powershell', 'pingtest.ps1'], returncode=1)

有没有办法让我的 powershell 脚本的实时结果显示在烧瓶请求中? (http,或 websocket 或任何其他方法?)

【问题讨论】:

    标签: python websocket


    【解决方案1】:

    我相信我从这里找到了答案:How to send the output of a long running Python script over a WebSocket?

    我将 subprocess 模块设置为一次读取一行,并将标准输出通过管道传输到 forloop,在该循环中可以读取每一行并将其发送到 websocket:

    @sock.route('/echo')
    def echo(ws):
        while True:
            data = ws.receive()
            with subprocess.Popen(['powershell', ".\pingtest.ps1"],stdout=subprocess.PIPE, bufsize=1,universal_newlines=True) as process:
                for line in process.stdout:
                    line = line.rstrip()
                    print(f"line = {line}")
                    ws.send(line)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      • 2010-11-17
      相关资源
      最近更新 更多