4

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

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, as fd = fdopen(p.get_open_files()[0].fd),但print fd.tell()仅返回文件中的第一个位置,该位置未在循环中更新。

有没有办法根据文件描述符获取文件中的当前实时位置?

4

1 回答 1

2

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

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

我不知道这是否是唯一的方法,但至少它工作正常。

解释: ftell 在文件描述符上?

于 2014-09-03T14:22:21.983 回答