简体   繁体   English

如何将 python 与 nodejs 集成

[英]How can I integrate python with nodejs

I want to use python scripts with my Node.JS server, but whenever I run the node server, the python script doesn't run.我想在我的 Node.JS 服务器上使用 python 脚本,但是每当我运行节点服务器时,python 脚本都不会运行。 It starts the server but no python runs.它启动服务器,但没有 python 运行。 I think it's in this part of the code but I'm not exactly sure.我认为它在这部分代码中,但我不确定。

My index.js:我的 index.js:

app.post("/readPython", (request, response) => {
 var dataToSend;
 const python = spawn('python', ['python/cookie.py'], "Kevin");

 python.stdout.on('data', function (data) {
  dataToSend = data.toString();
 });

 python.stderr.on('data', data => {
 console.error(`stderr: ${data}`);
 });

 python.on('exit', (code) => {
 console.log(`child process exited with code ${code}, ${dataToSend}`);
 response.sendFile(`${__dirname}/html/result.html`);
 });
});

My python script:我的 python 脚本:

import sys

print("Hello World!")

sys.stdout.flush()

I don't know exactly what I should expect but whatever it is, the script isn't running.我不知道我应该期待什么,但无论如何,脚本都没有运行。 Any help?有什么帮助吗?

the 3rd argument (options) in spawn() should be an object. spawn()中的第三个参数(选项)应该是 object。 I am assuming you are trying to send Kevin as argument.我假设您正试图将凯文作为论据。 It should be like它应该像

const python = spawn('python', ['helloworld.py',"Kevin"]);

python.stdout.on('data', (data)=> {

        console.log(data.toString());
       
    });

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

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