用Python连续交换数据

2024-04-29 13:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

一个用例是:

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

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

在node上我有这样的东西:

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脚本是:

^{pr2}$

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

我正确地需要python-shell模块,并且能够执行python脚本并返回数据(使用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

Tags: 脚本clientmodulesnodeapplibjsusers
1条回答
网友
1楼 · 发布于 2024-04-29 13:29:51

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

我很确定end只会在python脚本完成时执行,但是它恰好关闭了输入流而没有终止脚本。在

很抱歉我没注意到。在

相关问题 更多 >