简体   繁体   English

python os.read() 未读取正确的字节数

[英]python os.read() not reading correct number of bytes

I'm trying to read blocks from a binary file (oracle redo log) but I'm having a issue where, when I try to read a 512 byte block using os.read(fd,512) I am returned less than 512 bytes.我正在尝试从二进制文件(oracle 重做日志)中读取块,但我遇到了一个问题,当我尝试使用 os.read(fd,512) 读取 512 字节块时,返回的字节数少于 512 字节. (the amount differs depending on the block) (金额因区块而异)

the documentation states that "at most n Bytes" so this makes sense that I'm getting less than expected.文档指出“最多 n 字节”,所以我得到的比预期的少是有道理的。 How can I force it to keep reading until I get the correct amount of bytes back?如何强制它继续读取,直到我得到正确数量的字节?

I've attempted to adapt the method described here Python f.read not reading the correct number of bytes But I still have the problem我试图调整这里描述的方法Python f.read 没有读取正确的字节数但我仍然有问题

def read_exactly(fd, size):
    data = b''
    remaining = size
    while remaining:  # or simply "while remaining", if you'd like
        newdata = read(fd, remaining)
        if len(newdata) == 0:  # problem
            raise IOError("Failed to read enough data")
        data += newdata
        remaining -= len(newdata)
    return data


def get_one_block(fd, start, blocksize):
    lseek(fd, start, 0)
    blocksize = blocksize

    print('Blocksize: ' + str(blocksize))
    block = read_exactly(fd, blocksize)
    print('Actual Blocksize: ' + str(block.__sizeof__()))
    return block

which then returns the error: OSError: Failed to read enough data然后返回错误: OSError: Failed to read enough data

My code:我的代码:

from os import open, close, O_RDONLY, lseek, read, write, O_BINARY, O_CREAT, O_RDWR

def get_one_block(fd, start, blocksize):
    lseek(fd, start, 0)
    blocksize = blocksize

    print('Blocksize: ' + str(blocksize))
    block = read(fd, blocksize)
    print('Actual Blocksize: ' + str(block.__sizeof__()))

    return block

def main():
    filename = "redo_logs/redo03.log"
    fd = open(filename, O_RDONLY, O_BINARY)
    b = get_one_block(fd, 512, 512)

Output Output

Blocksize: 512
Actual Blocksize: 502

in this instance the last byte read is 0xB3 which is followed by 0x1A which i believe is the problem.在这种情况下,读取的最后一个字节是 0xB3,后面是 0x1A,我认为这是问题所在。

00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 
EF 42 B8 5A DC D1 63 1B A3 31 C7 5E 9F 4A B7 F4 
4E 04 6B E8 B3<<-- stops here -->>1A 4F 3C BF C9 3C F6 9F C3 08 02 
05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

Any help would be greatly appreciated:)任何帮助将不胜感激:)

You need to read inside a while loop and check the true number of bytes you've got.您需要在 while 循环中读取并检查您拥有的真实字节数。

If you got less you read again with the left delta.如果你得到的更少,你会用左边的增量再次阅读。

the while exits when you got what you expected or reached EOF.当您得到预期或达到 EOF 时,while 退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM