如何进行两个程序,Nodejs和Python进行交流?

发布于 2025-02-10 12:08:16 字数 236 浏览 4 评论 0原文

我有两个程序。 Nodejs中的服务器和Python中的脚本。

基本上,脚本刮擦并将数据写入JSON文件。

我想做的是使Nodejs服务器重置JSON文件,而无需更改Python程序。

我尝试了一个简单的写文件,但有时会输出随机字符。

我知道如何使用信号,但是我不知道用信号随机中断我的python脚本是个好主意。

我也知道如何使用管道,但这是个好主意吗?

我能做些什么 ?

I have two programs. A server in NodeJS and a script in Python.

Basically, the script scrapes and writes data to a JSON file.

What I want to do, is to make the NodeJS server reset the JSON file without altering with the Python program.

I tried a simple writeFile, but it outputs random characters sometimes.

I know how to use signals, but I don't know if it's a good idea to interrupt my Python script randomly with a signal.

I also know how to use pipes, but is it a good idea ?

What can I do ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

但可醉心 2025-02-17 12:08:16

您可以使用 python-shell 可以在nodejs中调用python脚本该脚本在内部呼吁等待脚本结束,并在结束覆盖或清除nodejs的JSON文件后。这样,当Nodejs进行JSON文件清洁时,您将100%确定Python脚本不会运行。

const promise = await new Promise((resolve, reject) => {
  PythonShell.run(
    `/SCRIPT_PATH.py`,
    {
        args: [''], // ARRAY OF ARGUMENTS TO THE PYTHON SCRIPT
    },
    function (err, result) {
      if (err) reject({ success: false, message: err });
      resolve({ success: true, message: result });
    }
  );
});
if (promise.success) {
  // REST OF YOUR CODE IF THE SCRIPTS EXECUTES SUCCESSFULLY
}

PS:结果变量是脚本的输出,如果在args array中需要的话,您可以将参数传递给Python脚本。

You can use python-shell to be able to call python scripts in NodeJS, and wrap that script call inside a Promise to wait for the script to end, and after it ends overwrite or clean the JSON file from NodeJS. In this way you'll be 100% sure that the python script is not running when NodeJS does the cleansing of the JSON file.

const promise = await new Promise((resolve, reject) => {
  PythonShell.run(
    `/SCRIPT_PATH.py`,
    {
        args: [''], // ARRAY OF ARGUMENTS TO THE PYTHON SCRIPT
    },
    function (err, result) {
      if (err) reject({ success: false, message: err });
      resolve({ success: true, message: result });
    }
  );
});
if (promise.success) {
  // REST OF YOUR CODE IF THE SCRIPTS EXECUTES SUCCESSFULLY
}

P.S.: The result variable is the output of your script and you are able to pass parameters to the python script if it's needed in the args array.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文