简体   繁体   中英

Nodejs InputStream Buffer convert to string using python

i have one application nodejs which request send to python using python-shell npm package. and python script read data and parse string.

nodejs file : teststr.js

let buf = `<html><body><p>Reply</p></body></html>`
var PythonShell = require('python-shell')
var options = {
    mode: 'binary',
    args: ['html'],
    scriptPath: __dirname + '/',
    pythonPath: '/usr/bin/python3'
}

var pyshell = new PythonShell('test.py', options)

pyshell.stdout.on('data', function (message) {
    console.log(message)
})

pyshell.send(buf)

pyshell.end(function (err) {
  if (err) {
    console.log('End Script' + err)
  }
})

Python File : test.py

import sys
import base64
import struct
import io

type = sys.argv[1]
html = ""
htmlBuffer = ""
for line in sys.stdin.buffer:
    htmlBuffer = io.BufferedReader(line)


#htmlBuffer = to_str(htmlBuffer) #htmlBuffer.decode('utf-8', errors='ignore').strip()
print("%s" % (htmlBuffer))

given Output is as below :

<Buffer 62 27 3c 68 74 6d 6c 3e 3c 62 6f 64 79 3e 3c 70 3e 52 65 70 6c 79 3c 2f 70 3e 3c 2f 62 6f 64 79 3e 3c 2f 68 74 6d 6c 3e 27 0a>

expect result :

<html><body><p>Reply</p></body></html>

EDIT:

You have probably something wrong in the code of test.py here in the post, because if I run it I get the error:

End ScriptError: AttributeError: 'bytes' object has no attribute 'readable'

But it does not matter, we can use this simple variant of test.py:

import sys
for line in sys.stdin:
    print(line.rstrip())

The point is, that your output is NOT the python output, but it means, that the argument message in the pyshell.stdout.on('data', function (message) {... is a Buffer object. So (sorry for the error in my previous post) we need to edit teststr.js by adding the toString() method.

pyshell.stdout.on('data', function (message) {
    console.log(message.toString())
})

Then it works. You don't have to worry about buffers in Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM