Pythonを使用して、オブジェクトをメモリにFTPにアップロードできますか?
質問
これが私が今していることです:
mysock = urllib.urlopen('http://localhost/image.jpg')
fileToSave = mysock.read()
oFile = open(r"C:\image.jpg",'wb')
oFile.write(fileToSave)
oFile.close
f=file('image.jpg','rb')
ftp.storbinary('STOR '+os.path.basename('image.jpg'),f)
os.remove('image.jpg')
ファイルをディスクに書き込み、それらを削除することを削除することは、避けるべきシステムでの追加作業のように思えます。 Pythonを使用して、オブジェクトをメモリにFTPにアップロードできますか?
解決
のため アヒルタイピング, 、ファイルオブジェクト(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()
コメントしたように、それはaを望んでいます ファイルのようなオブジェクト, 、確かにそれは特にファイルのようでさえありません、それはただ必要です read(n)
. stringio このような「メモリファイル」サービスを提供します。
他のヒント
import urllib
import ftplib
ftp = ftplib.FTP(...)
f = urllib.urlopen('http://localhost/image.jpg')
ftp.storbinary('STOR image.jpg', f)
任意のインメモリを使用できます ファイルのようなオブジェクト, 、 お気に入り BytesIO
:
from io import BytesIO
バイナリモードで動作します FTP.storbinary
:
f = BytesIO(b"the contents")
ftp.storbinary("STOR /path/file.txt", f)
ASCII/テキストモードと同様に FTP.storlines
:
f = BytesIO(b"the contents")
ftp.storlines("STOR /path/file.txt", f)
より高度な例については、参照してください。
所属していません StackOverflow