【问题标题】:Nodejs InputStream Buffer convert to string using pythonNodejs InputStream Buffer使用python转换为字符串
【发布时间】:2017-11-24 06:13:36
【问题描述】:

我有一个应用程序 nodejs,它请求使用 python-shell npm 包发送到 python。和python脚本读取数据并解析字符串。

nodejs 文件: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 文件: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))

给定的输出如下:

&lt;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&gt;

预期结果:

&lt;html&gt;&lt;body&gt;&lt;p&gt;Reply&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;

【问题讨论】:

    标签: python node.js buffer inputstream


    【解决方案1】:

    编辑:

    您可能在帖子中的 test.py 代码中有问题,因为如果我运行它,我会收到错误:

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

    不过没关系,我们可以使用test.py这个简单的变种:

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

    关键是,您的输出不是 python 输出,但这意味着 pyshell.stdout.on('data', function (message) {... 中的参数 message 是一个 Buffer 对象。所以(很抱歉我之前帖子中的错误)我们需要通过添加toString() 方法来编辑teststr.js。

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

    然后就可以了。您不必担心 Python 中的缓冲区。

    【讨论】:

    • 不,我想使用 python 处理 html 并将响应发送回 nodejs。目前我在 python 中接收输入作为缓冲区,所以我如何将缓冲区转换为字符串
    • 给定&lt;Buffer 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 0a&gt;
    猜你喜欢
    • 2017-07-28
    • 2013-08-31
    • 2018-01-23
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 2013-04-11
    • 2011-10-21
    相关资源
    最近更新 更多