python - 将大型 csv 文件从 NodeJS 发送到 python

标签 python node.js

我需要将大型 csv 文件从 Node 发送到 python。此代码适用于小文件,但不适用于大文件。我也尝试过生成过程。我不明白有什么问题。如果有人知道正确的代码请分享

代码:

const express=require('express')
const app=express()    
let p = require('python-shell');
const fs = require('fs');
let filledarray=[]

fs.createReadStream('data.csv')

.pipe(csv())

.on('data', (row) => {



filledarray.push(row)

})

.on('end', () => {

   console.log('CSV file successfully processed');

});

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



  var options = {
       args:
       [
           JSON.stringify(filledarray)
       ]
  }
  p.PythonShell.run('hello.py', options, function  (err, results)  {

         if(err) {
           console.error(err)
         }
         else{
            console.log(results)
            res.send(results)
         }

  });

})

app.listen('5000')

错误

 Error: spawn ENAMETOOLONG at ChildProcess.spawn (internal/child_process.js:394:11) at Object.spawn 
 (child_process.js:535:9)

最佳答案

您正在将大量数据作为参数发送给脚本 hello.py,这就是您收到 ENAMETOOLONG 的原因。

您需要更改 Python 脚本以从 stdin 接收数据,并使用 pyshell.send(data);

let pyshell = new PythonShell('hello.py', { mode: 'text' });

// sends a message to the Python script via stdin
pyshell.send('hello');

您可以使用以下 3 种模式之一:

  • 使用文本模式交换文本行
  • 使用json模式交换JSON片段
  • 使用二进制模式进行其他操作(数据按原样发送和接收)

在您的特定情况下,您可以使用 json 并单独发送每一行。然后在您的 python 脚本中,您可以使用以下内容,取自 python-shell examples

我不懂Python

import sys, json

# simple JSON echo script
for line in sys.stdin:
  print(json.dumps(json.loads(line)))
let pyshell = new PythonShell('hello.py', { mode: 'json' });

fs.createReadStream('data.csv')
.pipe(csv())
.on('data', (row) => {
   pyshell.send(row);
})

关于python - 将大型 csv 文件从 NodeJS 发送到 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59429629/

相关文章:

node.js - Nodejs - IBM Watson Speech To Text Websocket 连接错误

arrays - Node.js - 从函数返回数组

python - 使用 Python 跟踪重定向和 cookie

python - 尝试在 iOS 设备上使用 ReportLab 创建 PDF 时出现权限错误

python - 日志文件解析python

python - 重命名 Panda Series/DataFrame 的索引

javascript - Node.js 有模板引擎吗?

html - 如何通过 html 文件显示 MySQL 数据库中的内容?

windows - 某些 NPM 安装失败并显示 EPERM 50(Gulp 和其他)

python - 使用 NLTK 在 Python 中获取大量名词(或形容词);或 Python Mad Libs