【发布时间】:2015-05-05 15:16:48
【问题描述】:
我正在尝试使用请求下载文件,并在每次检索 100k 大小的文件时打印一个点,但最后打印出所有点。见代码。
with open(file_name,'wb') as file:
print("begin downloading, please wait...")
respond_file = requests.get(file_url,stream=True)
size = len(respond_file.content)//1000000
#the next line will not be printed until file is downloaded
print("the file size is "+ str(size) +"MB")
for chunk in respond_file.iter_content(102400):
file.write(chunk)
#print('',end='.')
sys.stdout.write('.')
sys.stdout.flush()
print("")
【问题讨论】:
-
哪些部分延迟了?一些
print()电话或sys.stdout.write()电话? -
猜想:访问
respond_file.content会强制请求全部完成,然后才能继续下一行。尝试删除size = ...和print("the file size is...行,看看你的点是否能更及时地打印出来。 -
@Kevin:我错过了,但猜测是正确的。
-
是的,是.content导致打印点延迟,根据答案可以解决。
标签: python python-3.x web-crawler python-requests