使用 python-shell 持续交换数据

2024-05-08

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

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

一个用例是:

  • Node启动,并唤醒python脚本
  • 节点客户端上的某些操作会导致它发送command到Python脚本
  • python 脚本计算它需要的内容并返回数据

I think 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');
});

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

我尝试了这个解决方案类似的问题 https://stackoverflow.com/questions/42462072/pythonshell-in-node-nwjs但在包装时出现错误hello端点中的消息。

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

当我打开时localhost:8000/hello I get 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 脚本完成时才会执行,但它恰好关闭输入流而不终止脚本。

为我的注意力不集中而道歉。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 python-shell 持续交换数据 的相关文章

随机推荐