错误:当尝试从nodejs发送长字符串到python脚本时,生成ENAMETOOLONG



我正试图编写一些代码,将采取由用户上传的图像并调整其大小。下面的代码适用于非常小的图像,但是当我尝试较大的图像时,我收到错误spawn ENAMETOOLONG。我相信这是因为base64字符串要大得多。我该怎么做才能将base64字符串发送给我的python脚本,而不管长度是多少?

server.js

const _arrayBufferToBase64 = (buffer)  => {
return Buffer.from(buffer).toString('base64');
};
// spawn new child process to call the python script
const python = spawn('python', ['./python/image_handler.py', _arrayBufferToBase64(imgData), filename]);
// collect data from script
python.stdout.on('data', function (pydata) {
console.log('Pipe data from python script ...');
});

python.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
});

image_handler.py

img_b64 = sys.argv[1]
img_bytes = base64.b64decode(img_b64)  # im_bytes is a binary image
img_file = io.BytesIO(img_bytes)  # convert image to file-like object
img = Image.open(img_file)   # img is now PIL Image object
img.thumbnail((300, 300))# resize image
img.save(sys.argv[2])  # Save Path
print('Finished')
sys.stdout.flush()

您试图将字符串作为参数传递给python,这超出了标准输入的限制。对于类似的问题,我发现最好的方法是使用python-shell。

您可以通过stdin以以下方式发送base64字符串(或任何大数据):(参考Python -shell关于在Node和Python之间交换数据的文档)

import {PythonShell} from 'python-shell';
let pyshell = new PythonShell('my_script.py', { mode: 'text' });
// sends a message to the Python script via stdin
pyshell.send('hello');
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
// end the input stream and allow the process to exit
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');
});

在初始化pyshell时,您可以尝试使用文本模式(以简单字符串的形式发送和接收数据)或二进制模式(按原样发送和接收数据)。

在python端,在image_handler.py,这样读:

~
img_b64 = input()
~

希望这对任何像我一样通过谷歌偶然发现这里的人有所帮助。

最新更新