获取Python中文件描述符的位置



比方说,我有一个原始的数字文件描述符,我需要根据它获得文件中的当前位置。

import os, psutil
# some code that works with file
lp = lib.open('/path/to/file')
p = psutil.Process(os.getpid())
fd = p.get_open_files()[0].fd  # int
while True:
    buf = lp.read()
    if buf is None:
        break
    device.write(buf)
    print tell(fd)  # how to find where we are now in the file?

在下面的代码中,lib是一个已编译的库,它不提供对文件对象的访问权限。在循环中,我使用嵌入式方法read,它返回处理后的数据。数据及其长度与文件位置无关,因此我无法用数学方法计算偏移量。

我尝试使用fdopen作为fd = fdopen(p.get_open_files()[0].fd),但print fd.tell()只返回了文件中的第一个位置,该位置在循环中没有更新。

有没有一种方法可以根据文件描述符获得文件中的当前实时位置?

所以,答案似乎很简单。我不得不使用带有SEEK_CUR标志的os.lseek

import os
print(os.lseek(fd, 0, os.SEEK_CUR))

我不知道这是否是唯一的方法,但至少效果很好。

已解释:是否打开文件描述符?

相关内容

最新更新