I've got two pieces of code that are both meant to do the same thing -- sit in a loop until a file is done being written to. They are both mainly used for files coming in via FTP/SCP.
我有两段代码,它们都是用来做相同的事情的——在一个循环中,直到一个文件被写入。它们都主要用于通过FTP/SCP进入的文件。
One version of the code does it using os.stat()[stat.ST_SIZE]
:
该代码的一个版本使用了os.stat()[stat.ST_SIZE]:
size1,size2 = 1,0
while size1 != size2:
size1 = os.stat(file_name)[stat.ST_SIZE]
time.sleep(300)
size2 = os.stat(file_name)[stat.ST_SIZE]
Another version does it with os.path.getsize()
:
另一个版本使用os.path.getsize():
size1,size2 = 0,0
while True:
size2 = os.path.getsize(file_name)
if size1 == size2:
break
else:
time.sleep(300)
size1 = size2
I've seen multiple instances where using the first method reports that the sizes are the same while the file is actually still growing. Is there some underlying reason why os.stat()
would incorrectly report while os.path.getsize()
would not? I'm not seeing any errors or exceptions come back.
我已经看到了多个实例,其中使用第一个方法报告的大小是相同的,而文件实际上仍然在增长。为什么os.stat()会不正确地报告,而os.path.getsize()不会?我没有看到任何错误或异常返回。
1 个解决方案
#1
17
In CPython 2.6 and 2.7, os.path.getsize()
is implemented as follows:
在CPython 2.6和2.7中,os.path.getsize()实现如下:
def getsize(filename):
"""Return the size of a file, reported by os.stat()."""
return os.stat(filename).st_size
From this, it seems pretty clear that there is no reason to expect the two approaches to behave differently (except perhaps due to the different structures of the loops in your code).
从这一点来看,显然没有理由期望这两种方法有不同的行为(除了可能由于代码中的循环结构不同)。
#1
17
In CPython 2.6 and 2.7, os.path.getsize()
is implemented as follows:
在CPython 2.6和2.7中,os.path.getsize()实现如下:
def getsize(filename):
"""Return the size of a file, reported by os.stat()."""
return os.stat(filename).st_size
From this, it seems pretty clear that there is no reason to expect the two approaches to behave differently (except perhaps due to the different structures of the loops in your code).
从这一点来看,显然没有理由期望这两种方法有不同的行为(除了可能由于代码中的循环结构不同)。