使用文件,可以对文件句柄进行迭代(不需要子进程打开cat):
with open('hugefile.log', 'r') as f:
for read_line in f:
print(read_line)
Python 通过读取直到\n 的所有字符来读取一行。要模拟逐行 I/O,只需调用 3 次即可。或读取并计算 3 个 \n 字符,但您必须处理文件结尾等...不是很有用,这样做不会获得任何速度。
with open('hugefile.log', 'r') as f:
while True:
read_3_lines = ""
try:
for i in range(3):
read_3_lines += next(f)
# process read_3_lines
except StopIteration: # end of file
# process read_3_lines if nb lines not divisible by 3
break
使用Popen 你可以做同样的事情,作为奖励添加poll 来监控过程(cat 不需要,但我想你的过程不同,这只是为了问题的目的)
import subprocess
task = subprocess.Popen("cat hugefile.log", shell=True, stdout=subprocess.PIPE)
while True:
line = task.stdout.readline()
if line == '' and task.poll() != None: break
rc = task.wait() # wait for completion and get return code of the command
支持编码的 Python 3 兼容代码:
line = task.stdout.readline().decode("latin-1")
if len(line) == 0 and task.poll() != None: break
现在,如果您想将文件拆分为给定数量的块:
- 你不能使用
Popen,原因很明显:你必须先知道输出的大小
- 如果您有一个文件作为输入,您可以执行以下操作:
代码:
import os,sys
filename = "hugefile.log"
filesize = os.path.getsize(filename)
nb_chunks = 1000
chunksize = filesize // nb_chunks
with open(filename,"r") as f:
while True:
chunk = f.read(chunksize)
if chunk=="":
break
# do something useful with the chunk
sys.stdout.write(chunk)