我有一个使用协议缓冲区的python应用程序,也有一个使用协议缓冲区的Java应用程序。我想要做的就是能够将消息(序列化后的二进制字符串)打印到标准输出。为此,我在Python应用程序中执行以下操作:
def printMessage(self,protobuf_msg):
数据= protobuf_msg.SerializeToString()
sys.stdout.write(数据)
sys.stdout.flush()
def main():
protobuf_msg = create_message()
controller.printMessage(protobuf_msg)
之后,我想通过管道输出(python pytonApp | java javaApp)并使用javaApp获取此数据并进行解析。我尝试了两种选择,使用Protobuf API可以做到这一点:
受保护的ProtobufMsg receiveMsg()引发异常{
ProtobufMsg消息= null;
消息= protobuf_msg.parseFrom(System.in);
返回消息;
}
我也尝试通过以下方式使用BufferedInputStream做到这一点:
受保护的ProtobufMsg receiveMsg()引发异常{
ProtobufMsg消息= null;
字节[]数据= receiveFromStd();
消息= protobuf_msg.parseFrom(数据);
返回消息;
}
公共字节[] receiveFromStd()引发异常{
BufferedInputStream输入=新的BufferedInputStream(System.in);
byte [] out =新的byte [1024];
int i=0; System.out.println("Entering While"); while((out[i] = (byte)input.read())!= -1){ i++;
System.out.println(“读取一个字节”);
}
byte[] data_out = new byte[i]; for(int l=0; l<data_out.length; l++){ data_out[l]=out[l]; } return data_out;
}
所以很明显我在做错事,但是我无法意识到我在做错什么,因为它停留在input.read()里面。
编辑:我决定改变策略,现在我先得到数据包的大小,然后再得到数据包,因为我正在使用input.read(byte [])函数...我正在使用的脚本如下:
FIFO_FILE=/tmp/named_$$ # unique name ($$ is the PID of the bash process running this script)
mkfifo $FIFO_FILE
export FIFO_FILE # export the env variable
ant run & # start a background process that reads the env variable and reads the fifo
cat > $FIFO_FILE # reads the standard input and writes to the fifo
rm $FIFO_FILE
我称之为:python pythonApp.py | ./script
。
readLine()
由于您具有二进制数据,因此无法使用。
不要使用Reader
API,因为您有二进制数据。只需使用BufferedInputStream
。
protobuf当然具有可以直接从流中读取的API。用那个。不要忘记刷新孩子的输出,否则数据将永远位于4K管道缓冲区中:
sys.stdout.write(data)
sys.stdout.flush()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句