TypeError: 'str' does not support the buffer interface while trying to pass a JSON object to a java process

TypeError: 'str' does not support the buffer interface while trying to pass a JSON object to a java process

我正在使用 Python 的子进程调用 Python 中的 Java 程序。 input/output 到 Java 程序是 JSON 对象。

这是我的代码,变量 args 基本上是程序接受的参数列表。

json_object = json.dumps([{"foo" :1, "bar": 2}])
p = subprocess.Popen(args,executable="/usr/bin/java",stdin=subprocess.PIPE, stdout =subprocess.PIPE)
p.stdin.write(json_object)
p.stdin.close()
out = json.load(p.stdout)

但是,我遇到了错误:TypeError: 'str' does not support the buffer interface

我正在使用 Python 3.4。我试图将 json_object 转换为字节,但这没有帮助。

您正在尝试将 Unicode 字符串写入子进程。首先对字符串进行编码,或者使用 universal_newlines=True 在 Unicode 模式下打开管道(包括换行符翻译),以便将 Unicode 字符串自动编码为系统的 standard 语言环境.

来自subprocess module FAQ section:

If universal_newlines is False the file objects stdin, stdout and stderr will be opened as binary streams, and no line ending conversion is done.

If universal_newlines is True, these file objects will be opened as text streams in universal newlines mode using the encoding returned by locale.getpreferredencoding(False). For stdin, line ending characters '\n' in the input will be converted to the default line separator os.linesep. For stdout and stderr, all line endings in the output will be converted to '\n'. For more information see the documentation of the io.TextIOWrapper class when the newline argument to its constructor is None.

对于JSON数据,我这里只编码成UTF-8;使用 Popen.communicate() 而不是自己写,因为这会更好地处理等待数据。您还需要再次 解码 JSON 数据。假设您的子进程也 returns UTF-8 编码 JSON 看起来像这样:

out_raw = p.communicate(json_object.encode('utf8'))[0]
out = json.loads(out_raw.decode('utf8'))