简体   繁体   English

如何让 Python 脚本在连接到 Node.JS 服务器的后台持续运行

[英]How to have a Python Script run constantly in the background connected to a Node.JS server

Currently I have a Node.JS server that needs to run a python script.目前我有一个需要运行 python 脚本的 Node.JS 服务器。 Part of this script imports some data from a server that takes time which is detrimental to the experience as this Python script needs to be ran frequently.此脚本的一部分从服务器导入一些数据,这对体验有害,因为此 Python 脚本需要频繁运行。

What I want is for the Node.JS server to run this Python script when the server is ran, then in the background constantly have it keep running, with the ability to (from the Node.JS server) call a python function that returns data.我想要的是 Node.JS 服务器在服务器运行时运行这个 Python 脚本,然后在后台不断地让它继续运行,并且能够(从 Node.JS 服务器)调用一个 python ZC1C425268E68385D1AB4507 返回数据4C17385D1AB507 .

So far I have this on the Node.JS server that runs a python script and outputs the response.到目前为止,我在运行 python 脚本并输出响应的 Node.JS 服务器上有这个。 This is repeated every time data is needed to be retrieved:每次需要检索数据时都会重复此操作:

const util = require('util');常量 util = 要求('util'); var options = { mode: 'text', args: [sentenceToUse] }; var options = { mode: 'text', args: [sentenceToUse] };

const readPy = util.promisify(PythonShell.run);
const test = await readPy("spacyTest.py", options);


    var response = test.toString();
    response = response.toString();
    response = response.replace(/'/g, '"');
    response = JSON.parse(response);
return(response);
console.log(test);

''' '''

How can I keep this running in the background without restarting the python script every time data is needed?每次需要数据时,如何在不重新启动 python 脚本的情况下使其在后台运行?

It seems you need to change the python script itself to keep running and respond to requests from its parent.看来您需要更改 python 脚本本身以继续运行并响应其父级的请求。 If the python script now runs and exits, there's nothing you can do from node.js to stop that.如果 python 脚本现在运行并退出,则您无法从 node.js 做任何事情来阻止它。 You need to change the python script.您需要更改 python 脚本。

Here are some options:以下是一些选项:

  1. The python script can regularly send data back to its parent on stdout and you can read that data from nodejs as it arrives. python 脚本可以定期将数据发送回其标准输出上的父级,并且您可以在 nodejs 到达时读取该数据。

  2. You can put a little local http server or socket.io server in the python script on a known port and have your nodejs parent communicate with that to make requests and get responses.您可以在已知端口上的 python 脚本中放置一点本地 http 服务器或 socket.io 服务器,并让您的 nodejs 父级与之通信以发出请求并获得响应。

  3. The Python-shell module also shows you how to communicate between node.js parent and the python script here in the doc , so that is an option too. Python-shell 模块还向您展示了如何在文档中的node.js 父级和 python 脚本之间进行通信,因此这也是一个选项。

Since options 1 and 3 are built-in already, I would probably start with one of those until you find some reason they aren't sufficient.由于选项 1 和 3 已经内置,我可能会从其中一个开始,直到您发现某些原因它们还不够。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM