【发布时间】:2017-03-06 08:13:12
【问题描述】:
我正在尝试通过标准输出将一个 numpy 数组从一个进程发送到另一个进程。
通过管道发送它需要我将它转换为字符串。 另一方面,我收到一个字节对象。这个字节对象现在已经封装了原始字节字符串。
我发现现在不可能将原始字节对象恢复为字节对象。 如果我解码字节对象,我会收到一个与我尝试过的所有恢复函数(np.frombuffer、pickle.loads)不兼容的字符串。
server.py
import subprocess
import numpy as np
p = subprocess.Popen(['python3', 'writer.py'], stdout=subprocess.PIPE)
while 1:
tmp = p.stdout.readline()
# doesn't fail but wrong size
array = np.frombuffer(tmp, dtype=np.uint8)
tmp = bytes.decode(tmp)
# fails because byte object is necessary
array = np.frombuffer(tmp, dtype=np.uint8)
array = array.reshape([1, 3, 5, 5, 1])
print(array.shape)
writer.py
import numpy as np
import sys
while 1:
array = np.zeros([1, 3, 5, 5, 1], dtype=np.int8)
string = array.tobytes()
sys.stdout.write(str(string))
sys.stdout.flush()
有没有将字符串转换为字节对象,而不对其进行编码? 这还能怎么做? 我想使用管道而不是其他一些解决方案中建议的共享内存,以使其更简单。此外,我需要它是并行但阻塞的,所以 Pipes 对我来说似乎很理想。
谢谢
【问题讨论】:
-
你先发送要来的对象的大小,然后从服务器的缓冲区中读取该大小?
-
@DanielSanchez 我不太明白,服务器端没有缓冲区?有标准输出,我可以从中读出发送的所有内容。但是阅读整个字符串不是问题。我想恢复原来的对象。
-
@Kilsen 你有没有在作家
sys.stdout.write(string)中尝试过而不转换为str? -
@kazemakase 是的,这是不可能的,因为
stdout.write需要一个字符串 -
@Kilsen
sys.stdout.write(b'abc')为我工作。为什么它不适合你?
标签: python python-3.x numpy pipe python-3.6