代码之家  ›  专栏  ›  技术社区  ›  VisioN

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

  •  4
  • VisioN  · 技术社区  · 12 年前

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

    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() 仅返回文件中的第一个位置,该位置未在循环中更新。

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

    1 回复  |  直到 12 年前
        1
  •  2
  •   Pablo Castellano    7 年前

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

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

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

    解释: ftell on a file descriptor?