在Python中获取文件描述符的位置 [英] Get position for file descriptor in Python
问题描述
import os,psutil
#一些与文件一起工作的代码
lp = lib.open('/ path / to / file')
p = psutil.Process (os.getpid())
fd = p.get_open_files()[0] .fd#int
而真:
buf = lp.read()
如果buf是None:
break
device.write(buf)
print tell(fd)#如何找到我们现在在文件中的位置?
在以下代码中, lib
图书馆,这并没有给予文件对象的访问权限。在循环中,我使用嵌入的方法读取
,它返回已处理的数据。数据和它的长度不涉及到文件的位置,所以我不能计算偏移数学。
我试图使用 fdopen ,如
fd = fdopen(p.get_open_files()[0] .fd)
,但是 print fd.tell )
只返回了文件中的第一个位置,在循环中没有更新。
有没有办法获得当前的实时在一个基于文件描述符的文件中的位置?
所以,答案似乎很容易。我不得不使用 os.lseek
SEEK_CUR
标志:
print os.lseek(fd,0,os.SEEK_CUR)
我不知道是不是只有方法,但至少它工作正常。
解释: ftell上的文件描述符?
Say, I have a raw numeric file descriptor and I need to get the current position in file based on it.
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?
In the following code lib
is a compiled library, that doesn't give access to the file object. In the loop I use the embedded method read
which returns the processed data. The data and it's length doesn't relate to the file position, so I can't calculate the offset mathematically.
I tried to use fdopen
, as fd = fdopen(p.get_open_files()[0].fd)
, but print fd.tell()
returned only the first position in the file, which was not updating in the loop.
Is there a way to get the current real time position in a file based on file descriptor?
So, the answer seems to be quite easy. I had to use os.lseek
with SEEK_CUR
flag:
print os.lseek(fd, 0, os.SEEK_CUR)
I don't know if it is the only approach, but at least it works fine.
INTERPRETED: ftell on a file descriptor?
这篇关于在Python中获取文件描述符的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!