0

I am trying to test performing a script on a flask python backend and send the realtime terminal result to the front end either as a websocket or an http request.

I tried to use flask_sock along with a function that runs a powershell script that pings google constantly. I tried to see the results on the front end but it only gave me process result, not the realtime result.

flask sock code:

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 code:

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()

I was expecting:

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

but instead I got:

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

is there way I can have the realtime results from my powershell script show up in a flask request? (Either http, or websocket or any other method?)

1 Answers1

0

I believe I figured out the answer from here: How to send the output of a long running Python script over a WebSocket?

I set the subprocess module to read one line at a time and to pipe the stdout to a forloop where each line can be read and sent to the 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)