簡體   English   中英

從 express 調用 python 腳本

[英]Call python script from express

我正在嘗試使用child_process運行 python 腳本,我正在使用打印hello的簡單腳本進行測試,但是我返回的 output 是undefinedhello

腳本.py

#!/usr/bin/python3

print ('hello')

應用程序.js

router.get('/hello', (req, res) => {
    const spawn = require('child_process').spawn;
    const py = spawn('/usr/bin/python3', ['./python/script.py']);
    
    let output;
    py.stdout.on("data", (data) => {
          output += data;
    });
    py.stdout.on("close", () => {
        console.log(output);
        res.sendStatus(200);
    });
});

我嘗試了幾個建議,但沒有一個奏效

const spawn = require('child_process').spawn;     // this should be out of the router

router.get('/hello', (req, res) => {
    
    const py = spawn('/usr/bin/python3', ['./python/script.py']);
    
    let output;
    py.stdout.on("data", (data) => {
          output += data.toString();
    });
    py.on("close", () => {                     // this differs 
        console.log(output);
        res.sendStatus(200);
    });
});

參考child_process

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM