簡體   English   中英

使用Node.js執行Python腳本

[英]Execute Python script with Node.js

我點擊HTML按鈕時嘗試執行Python腳本。 這兩個文件都在Node.js服務器上。 當我按下按鈕時,我在瀏覽器控制台中收到此消息:

app.js:5 Uncaught ReferenceError: runPython is not defined

我不知道如何編寫我的AJAX腳本來調用我的Node web服務器文件上的runPython()函數。 以下是我的代碼:

的index.html

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js">       </script>
</head>
<body>

<button id="myButton">Run Python Script</button>

<script src="app.js"></script>
</body>
</html>

app.js

$('#myButton').click(function() {
    $.ajax({
      url: "",
      success: function(data) {
         runPython();
      },
    });
});

webserver.js(node.js)

'use strict';
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');

let mimes = {
  '.htm': 'text/html',
  '.css': 'text/css',
  '.js': 'text/javascript'
}

//Have ajax call it to execute Python Script
function runPython(){
    let exec = require('child_process').exec;
    exec('python myscript.py', (error, stdout, stderr) => {
        console.log(stdout);
    });
}

function fileAccess(filepath) {
  return new Promise((resolve, reject) => {
    fs.access(filepath, fs.F_OK, error => {
      if(!error) {
        resolve(filepath);
      } else {
        reject(error);
      }
    });
  });
}

function streamFile(filepath) {
    return new Promise((resolve, reject) => {
        let fileStream = fs.createReadStream(filepath);

        fileStream.on('open', () => {
            resolve(fileStream);
        });

        fileStream.on('error', error => {
            reject(error);
        });
      });
}

function webserver(req, res) {
  // if the route requested is '/', then load 'index.htm' or else
  // load the requested file(s)

  let baseURI = url.parse(req.url);
  let filepath = __dirname + (baseURI.pathname === '/' ? '/index.htm' :  baseURI.pathname);
  let contentType = mimes[path.extname(filepath)];

  fileAccess(filepath)
    .then(streamFile)
    .then(fileStream => {
      res.writeHead(200, {'Content-type': contentType});
      //res.end(content, 'utf-8');
      fileStream.pipe(res);
    })
    .catch(error => {
      res.writeHead(404);
      res.end(JSON.stringify(error));
    });


}

http.createServer(webserver).listen(3000, () => {
  console.log('Webserver running on port 3000');
});

我應該如何編寫AJAX代碼以便運行webserver.js中的函數?

瀏覽器正在該URL加載腳本。 這被視為數據或文本。 瀏覽器通常不運行Python,因此按預期工作。

您需要向服務器發出一個ajax請求,該服務器將運行一些將調用您的python腳本的代碼。 您錯過了該過程的中間部分,只是將myscript.py的內容作為文本請求。

就像是:

$('#myButton').click(function() {
    $.ajax({
        url: "/invoke-script"
    });
});

我不熟悉Node,但我想你有某種控制器和執行命令的能力(可能使用https://www.npmjs.com/package/exec-sync )。 然后在該控制器中調用python腳本並使用輸出執行所需操作。

將此腳本視為可執行文件。 如果您的URL指向某個* .exe文件,則單擊該URL會告知Web瀏覽器下載該資源。 Python腳本也是如此。 如果你想運行一些python代碼,請嘗試使用簡單的HTTP服務器來處理HTTP請求。 這是在HTTP請求上執行某些操作的最常用方法。 檢查SimpleHTTPServerBaseHTTPServer的文檔。 在這里這里,您可以找到一些簡單服務器實現的代碼片段。

暫無
暫無

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

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