我需要将大型 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/