如何从J中的标准输入中读取python二进制字符串

2024-10-01 17:24:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用协议缓冲区的python应用程序,还有一个使用协议缓冲区的Java应用程序。我要做的只是能够将消息(序列化后的二进制字符串)打印到标准输出。为此,我在Python应用程序中执行以下操作:

def printMessage(self, protobuf_msg):

data = protobuf_msg.SerializeToString()

sys.stdout.write(data)

sys.stdout.flush()

def main():

protobuf_msg = create_message()

controller.printMessage(protobuf_msg)

在这之后,我希望通过管道输出这个输出(pythonpytonapp | javajavaapp),用javaApp获取这些数据并解析它。我尝试了两种方法,使用Protobuf API进行此操作:

protected ProtobufMsg receiveMsg() throws Exception{

ProtobufMsg message = null;

message = protobuf_msg.parseFrom(System.in);

return message;

}

我还尝试通过以下方式对BufferedInputStream执行此操作:

protected ProtobufMsg receiveMsg() throws Exception{

ProtobufMsg message = null;

byte[] data = receiveFromStd();

message = protobuf_msg.parseFrom(data);

return message;

}

public byte[]receiveFromStd()引发异常{

BufferedInputStream input = new BufferedInputStream(System.in);

byte[] out = new byte[1024];

int i=0;

System.out.println("Entering While");

while((out[i] = (byte)input.read())!= -1){

    i++;

System.out.println("One byte readed");

}

byte[] data_out = new byte[i];

for(int l=0; l<data_out.length; l++){

    data_out[l]=out[l];

}

return data_out;

}

很明显我做错了什么,但我没意识到我做错了什么, 因为它留在里面输入.读取()... 在

编辑: 我已经决定改变策略,现在我首先得到数据包的大小,然后是我使用的数据包的大小输入.读取(字节[])函数。。。 我使用的脚本如下:

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。在


Tags: the应用程序messageinputdatareturnmsgbyte
2条回答

您不能使用readLine(),因为您有二进制数据。在

  1. 不要使用ReaderAPI,你有二进制数据。只需使用BufferedInputStream

  2. protobuf肯定有一个API可以直接从流中读取。用那个。别忘了刷新子进程的输出,否则数据将永远保存在4K管道缓冲区中:

    sys.stdout.write(data)
    sys.stdout.flush()
    

我不能评论Python方面,但如果它是一个二进制消息,你可以这样做

    FileInputStream in = new FileInputStream(fileName);

    message = Extension01.Message.parseFrom(in);

或者如果是分隔消息:

^{pr2}$

不需要以字节形式读入

相关问题 更多 >

    热门问题