使用 python-shell 不断交换数据

Continuously exchange data using python-shell

我需要 运行 来自节点的一些 python 脚本。由于我的 python 脚本使用复杂的结构,我认为如果我只加载这些结构一次然后 运行 使用这些结构的一些特定脚本(任务)会更好。

在节点上,我想 运行 一个脚本永远(或者直到我说它可以终止)并继续向这个脚本发送点播消息。此脚本将创建一个进程,使用 python multiprocessing,以 运行 特定任务并再次开始侦听。

一个用例是:

我认为 python-shell 可以帮我解决这个问题

在节点上我有这样的东西:

var app = express();
app.listen(8000, function () {
    console.log('Example app listening on port 8000!');
});

var pyshell = new PythonShell('start.py', options);
pyshell.on('message', function (message) {
    handleAnswer(message);
});

pyshell.end(function (err, code, signal) {
    handleEnd(err, code, signal);
});

app.get('/hello', function (req, res) {
    pyshell.send('hello');
});

我的 start.py 脚本是:

import sys

def listen():
    while True:
        command = sys.stdin.readline()
        command = command.split('\n')[0]
        if command:
            print("Received CMD " + command)

if __name__ == '__main__':
    data = json.loads(sys.argv[1])
    listen()

我尝试了这个 的解决方案,但是在端点中包装 hello 消息时出现错误。

我正确地需要 python-shell 模块并且我能够执行 python 脚本和 return 数据(使用 print)。我的问题是启动脚本并在(随机)时间段后发送消息。

当我打开 localhost:8000/hello 我得到 Error: write after end

完整错误:

    Error: write after end
    at writeAfterEnd (_stream_writable.js:236:12)
    at Socket.Writable.write (_stream_writable.js:287:5)
    at Socket.write (net.js:717:40)
    at PythonShell.send (C:\Users\leonardo.schettini\Documents\recrutai\client\node_modules\python-shell\index.js:206:16)
    at C:\Users\leonardo.schettini\Documents\recrutai\client\app.js:27:12
    at Layer.handle [as handle_request] (C:\Users\leonardo.schettini\Documents\recrutai\client\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\leonardo.schettini\Documents\recrutai\client\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\leonardo.schettini\Documents\recrutai\client\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\leonardo.schettini\Documents\recrutai\client\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\leonardo.schettini\Documents\recrutai\client\node_modules\express\lib\router\index.js:281:22

好吧,我检查了我为 python-shell 所做的包装器,并在脚本创建后发现了一个 pyshell.end(callback) 调用。

我很确定 end 只会在 python 脚本完成时执行,但碰巧它在没有终止脚本的情况下关闭了输入流。

抱歉我疏忽了。