<p>你在找什么?(<a href="http://docs.python.org/library/stringio.html" rel="nofollow">doc page</a>)</strike></p>
<p><code>SFTPClient</code>的<code>get()</code>和<code>put()</code>函数采用路径而不是文件句柄,这使事情有点尴尬。</p>
<p>您可以为<code>paramiko.SFTPClient</code>编写一个包装器,以提供所需的功能。</p>
<p>以下是我未经测试的最佳尝试:</p>
<pre><code>from paramiko import SFTPClient
class SFTPClient2(SFTPClient):
def put(self, local_file, remotepath, callback=None, confirm=True):
fl = source_file
file_size = os.fstat(fl.fileno()).st_size
try:
fr = self.file(remotepath, 'wb')
fr.set_pipelined(True)
size = 0
try:
while True:
data = fl.read(32768)
if len(data) == 0:
break
fr.write(data)
size += len(data)
if callback is not None:
callback(size, file_size)
finally:
fr.close()
finally:
fl.close()
if confirm:
s = self.stat(remotepath)
if s.st_size != size:
raise IOError('size mismatch in put! %d != %d' % (s.st_size, size))
else:
s = SFTPAttributes()
return s
def get(self, remotepath, local_file, callback=None):
fr = self.file(remotepath, 'rb')
file_size = self.stat(remotepath).st_size
fr.prefetch()
try:
fl = local_file
try:
size = 0
while True:
data = fr.read(32768)
if len(data) == 0:
break
fl.write(data)
size += len(data)
if callback is not None:
callback(size, file_size)
finally:
fl.close()
finally:
fr.close()
s = os.fstat(fl.fileno())
if s.st_size != size:
raise IOError('size mismatch in get! %d != %d' % (s.st_size, size))
</code></pre>
<p>如果可以工作,<code>get</code>和<code>put</code>函数现在应该使用本地文件句柄而不是路径。</p>
<p>我所要做的就是从路径中删除打开文件的代码,并将获取文件大小的代码更改为使用<code>os.fstat</code>,而不是<code>os.stat</code>。</p>