python - Javascript 可以加载 Python pickle 转储的字符串但不能加载文件

标签 python node.js pickle

请看下面的测试代码,我可以使用 jpickle 库来解码 Python pickle 转储的字符串。

(base):~/python 
Python 3.7.3 (default, Mar 27 2019, 16:54:48) 
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> pickle.dumps('Hello Python!')
b'\x80\x03X\r\x00\x00\x00Hello Python!q\x00.'
>>> 
(base)~$ node
> const jpickle = require('jpickle');
undefined
> jpickle.loads('\x80\x03X\r\x00\x00\x00Hello Python!q\x00.')
'Hello Python!'

当我尝试将 pickle 字符串写入文件时,我无法将其加载回 nodejs。我的错误是什么?谢谢!

python 代码:

import pickle
with open('test.dat', 'wb') as fout:
    pickle.dump('Hello Python!', fout)

JS:

const fs = require('fs');
const jpickle = require('jpickle');
const binary = fs.readFileSync('test.dat');
const data = jpickle.loads(binary)
console.log(data)

错误信息:

node_modules/jpickle/lib/jpickle.js:341
            throw "Unhandled opcode '" + opcode + "'";
            ^
Unhandled opcode '128'

package.json中的jpickle,需要从GitHub上安装,目前是最新版本:

    "jpickle": "git+https://github.com/jlaine/node-jpickle.git"
  }

最佳答案

这似乎对我有用。感谢Tomalak用于输入。

const binary = fs.readFileSync('test.dat', "binary");

虽然这个解决方案似乎阻止了进程......

关于python - Javascript 可以加载 Python pickle 转储的字符串但不能加载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57798609/

相关文章:

python - 通过 SSH 将字典作为参数传递给 Python 脚本

javascript - 未处理的拒绝错误: Can't set headers after they are sent using Node

python - pickle 错误: AttributeError: Can't get attribute on <module '__main__' (built-in)>

python - 在一张图中绘制多个时间序列

python - 如何获取 subprocess.check_output() python 模块的输出?

node.js - 暴露用户唯一的 MongoDB _id 是否存在安全风险?

javascript - Passport 本地策略未将用户保存在 cookie 或 session 中

python 搁置: same objects become different objects after reopening shelve

python-3.x - Python 3没有write属性?

python /杰森 : If substring in string always results in TypeError: string member test needs char left operand