How would you pipe the stdout from subprocess to the websocket without needing to wait for a newline character? Currently, the code below only sends the stdout on a newline.
Code attached for the script being run by the subprocess. Is the output not being flushed properly from there?
send_data.py:
import asyncio
import websockets
import subprocess
import sys
import os
async def foo(websocket, path):
print ("socket open")
await websocket.send("successfully connected")
with subprocess.Popen(['sudo','python3', '-u','inline_print.py'],stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, universal_newlines=True) as p:
for line in p.stdout:
line = str(line.rstrip())
await websocket.send(line)
p.stdout.flush()
for line in p.stderr:
line = str(line.rstrip())
await websocket.send(line)
p.stdout.flush()
start_server = websockets.serve(foo, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
inline_print.py:
from time import sleep
import sys
loading = 'LOADING...LOADING...LOADING...LOADING...LOADING...'
for i in range(50):
print(loading[i], sep='', end=' ', flush=True)
sleep(0.1)
if end=' '
is changed to end='\n'
then the stdout from send_data.py
occurs in realtime.
js client:
var ws = new WebSocket('ws://localhost:8765/');
ws.onmessage = function(event) {
console.log(event.data);
};
I acknowledge this question is similar to these:
catching-stdout-in-realtime-from-subprocess
how-do-i-get-real-time-information-back-from-a-subprocess-popen-in-python-2-5
intercepting-stdout-of-a-subprocess-while-it-is-running
yet none of the solutions work without a newline character from the subprocess.