python - socketio.emit() doesn't work when interacting using Popen on Windows in a Thread -
i think quick code snippet better explain problem, please have @ this:
from flask import flask flask.ext.socketio import socketio threading import thread import subprocess import threading eventlet.green.subprocess import popen app = flask(__name__) socketio = socketio(app) def get_tasks_and_emit(): instance = popen(["tasklist"], stdout=subprocess.pipe, stderr=subprocess.pipe, bufsize=1) lines_iterator = iter(instance.stdout.readline, b"") data = "" line in lines_iterator: data += line.decode("utf8") socketio.emit("loaded", data) print("::: debug - returned tasks thread") @app.route("/") def index(): html = "<!doctype html>" html += "<script src=https://code.jquery.com/jquery-2.2.0.min.js></script>" html += "<script src=https://cdn.socket.io/socket.io-1.4.5.js></script>" html += "<script>" html += "var socket = io.connect(window.location.origin);" html += "socket.on('loaded', function(data) {alert(data);});" html += "function load_tasks_threaded() {$.get('/tasks_threaded');}" html += "function load_tasks_nonthreaded() {$.get('/tasks');}" html += "</script>" html += "<button onclick='load_tasks_nonthreaded()'>load tasks</button>" html += "<button onclick='load_tasks_threaded()'>load tasks (threaded)</button>" return html @app.route("/tasks") def tasks(): get_tasks_and_emit() print("::: debug - returned tasks without thread") return "" @app.route("/tasks_threaded") def tasks_threaded(): threading.thread(target=get_tasks_and_emit).start() return "" if __name__ == "__main__": socketio.run(app, port=7000, debug=true)
i running code on windows using eventlet, if don't use eventlet fine (but of course slower due werkzeug threading mode). (and checked , it's not working on linux either)
i hope can point me right direction. (my python version 3.5.1 way)
i found problem. apparently have monkey patch threading module, added
import eventlet eventlet.monkey_patch(thread=true)
and had problem long running programs. had same problem guy in stackoverflow post: using popen in thread blocks every incoming flask-socketio request
so added
eventlet.sleep()
to loop processes pipes.
edit: temoto pointed out, alternatively 1 can use threading module eventlet.green
this:
from eventlet.green import threading
Comments
Post a Comment