2010-04-19 5 views
2

여기에 내가 지금 뭘하는지입니다 : 다음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') 
디스크에 파일을 작성

및 imediately 그들을 피해야 시스템의 추가 작업처럼 보인다 삭제. 파이썬을 사용하여 메모리에있는 객체를 FTP로 업로드 할 수 있습니까? 때문에 duck-typing

+0

파일과 유사한 객체를 사용할 수 있습니까? –

답변

6

는, 파일 객체 (코드에서 f)는 단지 storbinary와 함께 작동하도록 .read(blocksize) 전화를 지원해야합니다. 이 같은 질문에 직면 할 때, 나는이 경우, 소스로 이동 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() 

, 그것은 단지 사실 그것도 특히 파일 -하지하는 file-like object 원 좋아, 그냥 read(n) 필요합니다. StringIO은 이러한 "메모리 파일"서비스를 제공합니다.

+1

좋은 답변입니다. 나는 이것이 효과가있을 것이라고 생각했지만 그 주위에 내 머리를 감쌀 수 없었다. – fsckin

1
import urllib 
import ftplib 

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