使用node js中的pythonshell软件包将python脚本连接到node js

时间:2020-01-09 05:10:06

标签: python node.js

我创建了一个python程序来从Wikipedia页面中抓取内容。我想使用具有pythonshell软件包的快速节点js在节点js服务器的localserver上显示此报废数据。这是我的Wiki.py(我想在本地主机上打印的python程序)和start.js(要在本地服务器上载的node js程序)的代码,但它仅在终端上打印,但不会将任何数据发送到本地主机。任务就是专门以这种方式进行。

Wiki.py代码:

from bs4 import BeautifulSoup
import requests

source = requests.get('https://en.wikipedia.org/wiki/Will_Smith').text
soup = BeautifulSoup(source,'html.parser')

heading = soup.find('h1',{'id':'firstHeading'}).text
print(heading)
print()

for item in soup.select("#mw-content-text"):
    required_data = [p_item.text for p_item in item.select("p")][3:6]
    print('\n'.join(required_data))

Start.js:节点js代码:

const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
  var myPythonScriptPath = 'Wiki1.py';
  const {PythonShell} = require("python-shell");
  var pyshell = new PythonShell(myPythonScriptPath);

  pyshell.on('message', function (message) {
    console.log(message);
});
})
app.listen(port, () => console.log(`Example app listening on port 
${port}!`))

2 个答案:

答案 0 :(得分:0)

您可以尝试使用node.js child_process模块​​

index.js

const express = require('express')
const { spawn } = require('child_process');
const app = express()
const port = 3000
app.get('/', (req, res) => {
    const pyProg = spawn('python', ['script.py']);
    pyProg.stdout.on('data', function(data) {
        console.log(data.toString());
        res.send(data.toString())
    });

})
app.listen(port, () => console.log(`Example app listening on port 
${port}!`))

script.py

print('data return from python')
print('data return from python')
print('data return from python')
print('data return from python')
print('data return from python')

答案 1 :(得分:0)

因此,如果您要查找的只是发送回“字符串”消息作为对API的响应,则


const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
  const myPythonScriptPath = 'wiki.py';
  const {PythonShell} = require("python-shell");
  const pyshell = new PythonShell(myPythonScriptPath);
  let string = ''

  pyshell.on('message', function (message) {
      console.log(message);
      string+=message
  });

  pyshell.end(function (err,code,signal) {
      if (err) throw err;
      console.log('The exit code was: ' + code);
      console.log('The exit signal was: ' + signal);
      console.log('finished', string);
      res.status(200).send(string)
  });  
})
app.listen(port, () => console.log(`Example app listening on port 
${port}!`))