python - 使用 python-shell 持续交换数据
问题描述
我需要从节点运行一些 python 脚本。由于我的 python 脚本使用复杂的结构,我认为如果我只加载这些结构一次然后使用这些结构运行一些特定的脚本(任务)会更好。
在节点上,我想永远运行一个脚本(或者直到我说它可以终止)并继续向这个脚本发送按需消息。该脚本将使用 python 创建一个进程multiprocessing
来运行特定任务并再次开始监听。
一个用例是:
- 节点启动,并唤醒 python 脚本
- 节点客户端上的某些操作导致它向
command
python 脚本发送 - python脚本计算它需要什么并返回数据
我认为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 脚本并返回数据(使用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 脚本完成时才会执行,但它碰巧在不终止脚本的情况下关闭了输入流。
为我缺乏关注而道歉。
推荐阅读
- swift - 我怎样才能得到绝对值的 ARAnchor 的偏航、俯仰、滚动?
- webpack - Webpack:在生产构建中使用 webpack-manifest-plugin 处理静态资产
- swift - 尝试从 firebase 数据库中检索类别列表( swift )
- python - Django 2.1:如何获取每个对象中的对象列表,其中包含具有指向它们的外键的对象
- linux - 上传/下载较大文件时,服务器不返回任何内容(无标题、无数据)
- c# - .NET 列表
.Sort 使用 introsort,为什么最坏的情况是 O(n^2)? - mysql - MySQL 和 Laravel - 在之前和之后检查现有记录
- angular - Angular中canactivate方法中的API调用
- php - 如何清理查询以接受表名作为参数 PDO php
- angular6 - 无法使用 HttpTestController 在 Jasmine 和 Karma 中模拟 HttpClient