因为duck-typing,文件对象(f
在你的代码中)只需要支持.read(blocksize)
调用就可以使用storbinary
。当遇到这样的问题时,我会去源头,在本例中是 lib/python2.6/ftplib.py:
def storbinary(self, cmd, fp, blocksize=8192, callback=None):
"""Store a file in binary mode. A new port is created for you.
Args:
cmd: A STOR command.
fp: A file-like object with a read(num_bytes) method.
blocksize: The maximum data size to read from fp and send over
the connection at once. [default: 8192]
callback: An optional single parameter callable that is called on
on each block of data after it is sent. [default: None]
Returns:
The response code.
"""
self.voidcmd('TYPE I')
conn = self.transfercmd(cmd)
while 1:
buf = fp.read(blocksize)
if not buf: break
conn.sendall(buf)
if callback: callback(buf)
conn.close()
return self.voidresp()
正如所评论的,它只需要一个类似文件的对象,实际上它甚至不是特别类似文件,它只需要read(n)
. StringIO提供了这样的“内存文件”服务。