簡體   English   中英

從節點生成子進程以運行 python 腳本返回 500

[英]Spawn child process from node to run python script returns 500

我正在嘗試生成一個子進程以從 Node.js 運行 python 腳本。 我收到以下請求:

/webcrawler?source=http://www.pygamers.com&method=BFS&nodeCount=3&depth=0&keyword=game

我已驗證我的參數輸入正確。 這是我為處理app.js中的請求而設置的代碼:

app.get('/webcrawler', function(req, res){
  var python = require('child_process').spawn(
  'python',
  ["WebCrawler/Webcrawler.py"
  , req.query.source
  , req.query.method
  , req.query.nodeCount
  , req.query.depth
  , req.query.keyword]
  );
  var output = "";
  python.stdout.on('data', function(data){ output += data });
  python.on('close', function(code){
    if (code !== 0) {
        return res.send(500, code);
    }
    return res.send(200, output);
  });
});

我正在調用我的 Python 腳本Webcrawler.py ,它位於 WebCrawler 目錄中。 WebCrawler 目錄與app.js位於同一目錄中。

但是,這個請求給我一個 500,我一直沒弄清楚為什么。 看來我一定是錯誤地生成了子進程。 為此,我將此答案用作 model。

它必須是絕對路徑,例如/home/username/Webcrawler/webcrawler.py

聽起來像是路徑問題。 還要簽出python-shell軟件包。 使您的生活變得如此輕松。

你可以在 npm -native-python上查看這個 package

它提供了一種非常簡單而強大的方法來從節點運行 python 函數可能會解決您的問題。 從'@guydev/native-python'導入{runFunction}

const example = async () => {
   const input = [1,[1,2,3],{'foo':'bar'}]
   const { error, data } = await runFunction('/path/to/file.py','hello_world', '/path/to/python', input)

   // error will be null if no error occured.
   if (error) {
       console.log('Error: ', error)
   }

   else {
       console.log('Success: ', data)
       // prints data or null if function has no return value
   }
}

python模塊

# module: file.py

def hello_world(a,b,c):
    print( type(a), a) 
    # <class 'int'>, 1

    print(type(b),b)
    # <class 'list'>, [1,2,3]

    print(type(c),c)
    # <class 'dict'>, {'foo':'bar'}

暫無
暫無

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

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