簡體   English   中英

將數組從 python 傳遞到外部 express.js

[英]Pass array from python to external express.js

在后端,我有一個 python 程序(vmstats.py),它將字符串數據存儲在 vmonoff[] 中:

vmstats.py

import json
from proxys import ProxyServer

vmonoff = []

proxys = ProxyServer('XXXXXX','UUUUUU','PPPPPP')

for b in proxys.listeners:
    if "MYVMNAME" in b.vname:
        if b.stat=="UP":
            vmonoff.append('./images/vm_on.png')
        else:
            vmonoff.append('./images/vm_off.png')
        
        print('{:<10}'.format(b.vname), '{:<8}'.format('Status:'), '{:>6}'.format(b.stat))

response = json.dumps(vmonoff)

exec.controller.js

const {exec} = require('child_process');
const path = require('path');
const fs = require('fs');
const htmlFile = path.join(__dirname, '/index.html');

exports.executeReport = (req, res) => {
    execute("python3 ./src/vmstats.py", res);

}

var responseObject = JSON.parse(response);

const execute = (command, res) => {
    exec(command, (error, stdout, stderr) => {
        if (error) {
            res.send({result: `error: ${error.message}`});
            return;
        }
        if (stderr) {
            res.send({result: `stderr: ${stderr}`});
            return;
        }
        createHtmlFile(stdout);
        res.sendFile(htmlFile);
        return;
    });
}

const createHtmlFile = (stdout) => {
    const rows = stdout.split('\n');
    const content = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>

<div class="container">
    <div style="text-align: center">
    <h3>TEST</h3>
    <br>
    </div>

</div>

</body>
</html>`

    fs.writeFileSync(htmlFile, content);
}

在前端(exec.controller.js),我嘗試使用:

var responseObject = JSON.parse(響應)

但我得到了ReferenceError: response is not defined

如何將vmonoff[]從 python 轉移到外部 express.js?

首先,您的 python 腳本似乎對stdout沒有 output 任何內容(通常使用類似print的內容完成),因此,Node JS 沒有什么可從那里讀取的。

除了createHtmlFile中的rows變量之外,沒有在任何地方使用。

在 python 腳本中,您需要打印數組:

response = json.dumps(vmonoff)
print(response)

在節點腳本中, stdout是你獲取數據的地方,你可以在那里解析它並進一步處理它:

const execute = (command, res) => {
    exec(command, (error, stdout, stderr) => {
        if (error) {
            res.send({result: `error: ${error.message}`});
            return;
        }
        if (stderr) {
            res.send({result: `stderr: ${stderr}`});
            return;
        }
        var responseObject = JSON.parse(stdout);
        createHtmlFile(responseObject);
        res.sendFile(htmlFile);
        return;
    });
}

然后在createHtmlFile中,您可以構造 HTML (例如,迭代數組元素,或者可能使用.join而不是.split ,尚不清楚 HTML 應該是什么樣子......)

暫無
暫無

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

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