合并两个代码 [英] Merge Two codes

查看:66
本文介绍了合并两个代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Node js 中有 2 个文件.我想合并这 2 个文件,但我遇到了问题..这个文件从python文件调用函数

const app = express()让 runPy = new Promise(function(success, nosuccess) {const { spawn } = require('child_process');const pyprog = spawn('python', ['./ml.py']);pyprog.stdout.on('数据',函数(数据){成功(数据);});pyprog.stderr.on('data', (data) => {没有成功(数据);});});app.get('/', (req, res) => {res.write('欢迎\n');runPy.then(function(testMLFunction) {console.log(testMLFunction.toString());res.end(testMLFunction);});})app.listen(4000, () => console.log('应用程序监听端口 4000!'))

python 文件 ml.py

def testMLFunction():返回来自 Python 的你好"

打印(testMLFunction())

以下文件适用于使用 post 方法点击按钮

var fs = require('fs');var server = http.createServer(function (req, res) {if (req.method === "GET") {res.writeHead(200, { "Content-Type": "text/html" });fs.createReadStream("./form.html", "UTF-8").pipe(res);} else if (req.method === "POST") {var 结果 = "";req.on(数据",函数(块){console.log(chunk.toString());结果 = 块;//body=body.toUpperCase;});req.on("结束", function(){res.writeHead(200, { "Content-Type": "text/html" });res.end(结果);});}}).听(3000);

我该怎么做..

解决方案

这里有几个问题.我会尽量解释清楚.

  1. 您忘记添加代码 var express = require('express')
  2. 您做出的承诺 runPy 必须包含在一个函数中,而您的方法将在加载脚本本身时立即启动承诺.
  3. 您正在解析/拒绝第一个传入的输出,您不应该这样做,因为您将无法知道 shell 中真正发生了什么.您需要存储这些输出行,这是您了解脚本告诉您的内容的唯一方法.
  4. runPy 中,您必须解析/拒绝 pyprogr close 事件.
  5. 你不能直接访问另一个脚本的方法,不管是py、sh、bat、js那种文件.但是,您可以通过向 shell 传递参数来访问它的内部函数,当然,该脚本必须具有处理这些参数所需的逻辑.
  6. 当使用 spawn/exec 时,你必须记住你不是执行脚本的用户,node 用户是,所以可能会出现不同的结果.
  7. 最重要的是,您的目标脚本必须PRINT/ECHO 到shell,不能返回!最好的方法是打印一些 json 字符串,并在 shell 关闭后在 javascript 中解析它,这样您就可以访问对象而不是字符串.

您将在下面找到适用于您的用例的演示,我更改了 python 文件,以便它可以打印某些内容.

ml.py

print('我是ml.py的输出')

index.js

const express = require('express');const app = express()let runPy = function () {//承诺现在被包装在一个函数中,因此它不会在脚本加载时触发返回新的承诺(功能(成功,不成功){const {spawn} = require('child_process');const pyprog = spawn('python', ['./ml.py'], {shell: true});//添加 shell:true 以便节点将与您的系统 shell 一起生成它.让 storeLines = [];//存储来自脚本的打印行让 storeErrors = [];//存储错误发生pyprog.stdout.on('数据',函数(数据){storeLines.push(data);});pyprog.stderr.on('data', (data) => {storeErrors.push(data);});pyprog.on('close', () => {//如果我们有错误将拒绝承诺,我们稍后会抓住它如果(storeErrors.length){nosuccess(new Error(Buffer.concat(storeErrors).toString()));} 别的 {成功(商店线);}})})};let path = require('path');app.use(express.json());app.use(express.urlencoded({extended: true }));//您需要设置此项,以便您可以捕获 POST 请求app.all('/', (req, res) => {//我已将其从 .get 更改为 .all 以便您可以在此处捕获 get 和 post 请求console.log('post params', req.body);if(req.body.hasOwnProperty('btn-send')){运行Py().then(函数(pyOutputBuffer){let message = '你发送了这个参数:\n' +JSON.stringify(req.body, null,2) + '\n';消息 += Buffer.concat(pyOutputBuffer).toString();res.end(消息);}).catch(控制台.log)}别的{res.sendFile(path.join(__dirname,'form.html'));//你需要一个'file.html'的绝对路径}});app.listen(4000, () => console.log('应用程序监听端口 4000!'));

form.html

你好

<form action="/" method="post"><input type="text" value="" name="some-text"/><button type="submit" value="1" name="btn-send" >按我!</button></表单>

I have 2 files in Node js .I want to merge these 2, but I am facing problem.. This file calls function from python file

const app = express()

let runPy = new Promise(function(success, nosuccess) {

    const { spawn } = require('child_process');
    const pyprog = spawn('python', ['./ml.py']);

    pyprog.stdout.on('data', function(data) {

        success(data);
    });

    pyprog.stderr.on('data', (data) => {

        nosuccess(data);
    });
});

app.get('/', (req, res) => {

    res.write('welcome\n');

    runPy.then(function(testMLFunction) {
        console.log(testMLFunction.toString());
        res.end(testMLFunction);
    });
})
app.listen(4000, () => console.log('Application listening on port 4000!'))

python file ml.py

def testMLFunction():
return "hello from Python"

print(testMLFunction())

Below file works on button click with post method

var fs = require('fs');

var server = http.createServer(function (req, res) {

    if (req.method === "GET") {
        res.writeHead(200, { "Content-Type": "text/html" });
        fs.createReadStream("./form.html", "UTF-8").pipe(res);
    } else if (req.method === "POST") {

        var result = "";
        req.on("data", function (chunk) {
            console.log(chunk.toString());

            result = chunk;
            //body=body.toUpperCase;
        });

        req.on("end", function(){
            res.writeHead(200, { "Content-Type": "text/html" });
            res.end(result);
        });
    }

}).listen(3000);

how can I do that..

解决方案

There are several things wrong here. I will explain as plain as possible.

  1. You forgot to add in your code var express = require('express')
  2. The promise you made, runPy, must be wrapped in a function, whereas your approach will instantly start the promise upon loading the script itself.
  3. You are resolving/rejecting on first incoming output, you shouldn't do that because you won't be able to know what really happened in the shell. You need to store those output lines, this is the only way of you knowing what the script tells you.
  4. In runPy you must resolve/reject upon pyprogr close event.
  5. You cannot access directly the method of another script, no matter what that kind of file that is a py, sh, bat, js. However, you can access internal functions of it by passing arguments to the shell, and of course, that script must have the logic required to deal with those arguments.
  6. When using spawn/exec you must keep in mind that YOU ARE NOT the user executing the script, the node user is, so different outcomes may occur.
  7. Most importantly, your targeted script must PRINT/ECHO to shell, no returns! The best approach would be to print some json string, and parse it in javascript after the shell is closed, so you can have access to an object instead of a string.

Below you will find a demo for your use case, i changed the python file so it can print something.

ml.py

print('I\'m the output from ml.py')

index.js

const express = require('express');
const app = express()

let runPy = function () { // the promise is now wrapped in a function so it won't trigger on script load
    return new Promise(function (success, nosuccess) {

        const {spawn} = require('child_process');
        const pyprog = spawn('python', ['./ml.py'], {shell: true}); // add shell:true so node will spawn it with your system shell.

        let storeLines = []; // store the printed rows from the script
        let storeErrors = []; // store errors occurred
        pyprog.stdout.on('data', function (data) {
            storeLines.push(data);
        });

        pyprog.stderr.on('data', (data) => {
            storeErrors.push(data);
        });
        pyprog.on('close', () => {
            // if we have errors will reject the promise and we'll catch it later
            if (storeErrors.length) {
                nosuccess(new Error(Buffer.concat(storeErrors).toString()));
            } else {
                success(storeLines);
            }
        })
    })
};

let path = require('path');
app.use(express.json());
app.use(express.urlencoded({ extended: true })); // you need to set this so you can catch POST requests
app.all('/', (req, res) => { // i've change this from .get to .all so you can catch both get and post requests here

    console.log('post params', req.body);

    if(req.body.hasOwnProperty('btn-send')){

        runPy()
            .then(function (pyOutputBuffer) {

                let message = 'You sent this params:\n' +JSON.stringify(req.body, null,2) + '\n';
                message += Buffer.concat(pyOutputBuffer).toString();

                res.end(message);

            })
            .catch(console.log)
    }else{
        res.sendFile(path.join(__dirname,'form.html')); // you need an absolute path to 'file.html'
    }

});
app.listen(4000, () => console.log('Application listening on port 4000!'));

form.html

<div>hello there</div>
<form action="/" method="post">
    <input type="text" value="" name="some-text"/>
    <button type="submit" value="1" name="btn-send" >Press me!</button>
</form>

这篇关于合并两个代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆