使用Lambda冻结程序在timeit内调用ftplib retrbinary()冻结程序

时间:2018-07-19 14:10:57

标签: python-2.7 lambda ftp-client ftplib

我正在尝试收集有关小型局域网中网络问题的一些指标,其中SSH有时会断开连接,并且ping会显示出巨大的延迟(长达一分钟而不是不到一秒钟!)。

使用timeit(我已经读到,这是在调用某些代码段时检查经过的执行时间的好方法)我尝试从也在本地运行的FTP服务器下载一些数据,测量时间并存储放在日志文件中。

from ftplib import FTP
from timeit import timeit
from datetime import datetime

ftp = FTP(host='10.0.0.8')
ftp.login(user='****', passw='****')
ftp.cwd('updates/')
ftp.retrlines('LIST')

# Get timestamp when the download starts
curr_t = datetime.now()

print('Download large file and measure the time')
file_big_t = timeit(lambda f=ftp: f.retrbinary('RETR update_big', open('/tmp/update_big', 'wb').write))

print('Download medium file and measure the time')
file_medium_t = timeit(lambda f=ftp: f.retrbinary('RETR file_medium ', open('/tmp/file_medium ', 'wb').write))

print('Download small file and measure the time')
file_small_t = timeit(lambda f=ftp: f.retrbinary('RETR update_small', open('/tmp/update_small', 'wb').write))

# Write timestamp and measured timings to file
# ...

如果我在没有retrbinary(...)的情况下呼叫timeit,它将正常工作。但是,上面的代码会导致脚本在第一次timeit调用之后立即冻结。

1 个答案:

答案 0 :(得分:0)

万一有人想做我在问题中描述的事情,我找到了解决方法here。由于某种原因,将lambda直接传递给timeit会导致我已经提到的行为。但是,如果先将相同 lambda传递给timeit.Timer的实例,然后调用该实例的timeit()函数,它将起作用。

对于上面的示例(我们仅取file_big_t

file_big_timer = Timer(lambda f=ftp: f.retrbinary('RETR update_big', open('/tmp/update_big', 'wb').write))
file_big_t = file_big_timer.timeit()
相关问题