Frage

Hier ist, was ich tue jetzt:

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')

Schreiben von Dateien auf der Festplatte und dann imediately sie auf dem System scheint, wie zusätzliche Arbeit zu löschen, die vermieden werden sollten. Kann ich ein Objekt im Speicher zu FTP mit Python?

laden
War es hilfreich?

Lösung

Aufgrund der duck-typing , das Dateiobjekt (f in Ihrem Code) muss nur unterstützen die .read(blocksize) Aufruf an die Arbeit mit storbinary. Wenn sie mit Fragen wie diese konfrontiert ist, gehe ich zu der Quelle, in diesem Fall 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()

Wie kommentierte es nur will ein dateiähnliche Objekt , in der Tat sei es nicht einmal besonders Datei-like, es muss nur read(n). StringIO bietet solche "Speicherdatei" Dienste.

Andere Tipps

import urllib
import ftplib

ftp = ftplib.FTP(...)
f = urllib.urlopen('http://localhost/image.jpg')
ftp.storbinary('STOR image.jpg', f)

Sie können eine beliebige In-Memory verwenden Datei-ähnliches Objekt , wie BytesIO :

from io import BytesIO

Es funktioniert sowohl im Binär-Modus mit FTP.storbinary :

f = BytesIO(b"the contents")
ftp.storbinary("STOR /path/file.txt", f)

sowie in ascii / Textmodus mit FTP.storlines

f = BytesIO(b"the contents")
ftp.storlines("STOR /path/file.txt", f)

Für fortgeschrittenere Beispiele finden Sie unter:

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top