gpt4 book ai didi

python - 在 Windows 上的线程中使用 Popen 进行交互时,socketio.emit() 不起作用

转载 作者:行者123 更新时间:2023-11-30 23:00:32 29 4
gpt4 key购买 nike

我认为快速的代码片段可以更好地解释我的问题,所以请看一下:

from flask import Flask
from flask.ext.socketio import SocketIO
from threading import Thread
import subprocess
import threading
from 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 = ""
for line in lines_iterator:
data += line.decode("utf8")

socketio.emit("loaded", data)

print("::: DEBUG - returned tasks with 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)

我使用 eventlet 在 Windows 上运行此代码,如果我不使用 eventlet 一切都很好(但当然,由于 werkzeug 线程模式,速度要慢得多)。 (我刚刚检查过,它在 Linux 上也不起作用)

我希望有人能指出我正确的方向。 (顺便说一句,我的Python版本是3.5.1)

最佳答案

我发现了问题。显然你必须修补线程模块,所以我添加了

import eventlet
eventlet.monkey_patch(thread=True)

然后我还遇到了长时间运行的程序的问题。我和 StackOverflow 帖子中的人遇到了同样的问题: Using Popen in a thread blocks every incoming Flask-SocketIO request

所以我添加了

eventlet.sleep()

到处理管道的 for 循环。

编辑:正如 temoto 指出的,或者也可以只使用 eventlet.green 中的线程模块,如下所示:

from eventlet.green import threading 

关于python - 在 Windows 上的线程中使用 Popen 进行交互时,socketio.emit() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35235797/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com